browser-extensions

Building a browser extension

Building browser extensions is a fun and interesting way to think about the performance of your apps while building a different type of web asset. This module includes lessons on how browsers work and how to deploy a browser extension, how to build a form, call an API, and use local storage, and how to gauge the performance of your website and improve it. You'll build a browser extension that works on Edge, Chrome, and Firefox. This extension, which is like a mini web site that is tailored to a very specific task, checks the C02 Signal API for a given region's electricity usage and carbon intensity, and returns a reading on the region's carbon footprint. This extension can be called ad hoc by a user once an API key and region code is input into a form to determine local electricity usage and thereby offer data that can influence a user's electricity decisions. For example, it may be preferable to delay running a clothes dryer (a carbon-intense activity) during a period of high electricity usage in your region. ### Topics 1. About the browser 2. Forms and local storage 3. Background tasks and performance ### Credits ## Credits The idea for this web carbon trigger was offered by Asim Hussain, lead at Microsoft of the Green Cloud Advocacy team and author of the Green Principles. It was originally a web site project. The structure of the browser extension was influenced by Adebola Adeniran's COVID extension. The concept behind the 'dot' icon system was suggested by the icon structure of the Energy Lollipop browser extension for California emissions. These lessons were written with ♥️ by Jen Looper

web,development

Browser Extension Project Part 1: All about Browsers

## Pre-Lecture Quiz Pre-lecture quiz ### Introduction Browser extensions are mini-applications that enhance your web browsing experience. Like Tim Berners-Lee's original vision of an interactive web, extensions extend the browser's capabilities beyond simple document viewing. From password managers that keep your accounts secure to color pickers that help designers grab perfect shades, extensions solve everyday browsing challenges. Before we build your first extension, let's understand how browsers work. Just as Alexander Graham Bell needed to understand sound transmission before inventing the telephone, knowing browser fundamentals will help you create extensions that integrate seamlessly with existing browser systems. By the end of this lesson, you'll understand browser architecture and have started building your first extension. ## Understanding Web Browsers A web browser is essentially a sophisticated document interpreter. When you type "google.com" into the address bar, the browser performs a complex series of operations - requesting content from servers worldwide, then parsing and rendering that code into the interactive web pages you see. This process mirrors how the first web browser, WorldWideWeb, was designed by Tim Berners-Lee in 1990 to make hyperlinked documents accessible to everyone. ✅ A little history: The first browser was called 'WorldWideWeb' and was created by Sir Timothy Berners-Lee in 1990. ### How Browsers Process Web Content The process between entering a URL and seeing a webpage involves several coordinated steps that happen within seconds: Here's what this process accomplishes: - Translates the human-readable URL into a server IP address through DNS lookup - Establishes a secure connection with the web server using HTTP or HTTPS protocols - Requests the specific web page content from the server - Receives HTML markup, CSS styling, and JavaScript code from the server - Renders all content into the interactive web page you see ### Browser Core Features Modern browsers provide numerous features that extension developers can leverage: Understanding these features helps you: - Identify where your extension can add the most value - Choose the right browser APIs for your extension's functionality - Design extensions that work efficiently with browser systems - Ensure your extension follows browser security best practices ### Cross-Browser Development Considerations Different browsers implement standards with slight variations, similar to how different programming languages might handle the same algorithm differently. Chrome, Firefox, and Safari each have unique characteristics that developers must consider during extension development. Key considerations for extension development: - Test your extension across Chrome, Firefox, and Edge browsers - Adapt to different browser extension APIs and manifest formats - Handle varying performance characteristics and limitations - Provide fallbacks for browser-specific features that may not be available ✅ Analytics Insight: You can determine which browsers your users prefer by installing analytics packages in your web development projects. This data helps you prioritize which browsers to support first. ## Understanding Browser Extensions Browser extensions solve common web browsing challenges by adding functionality directly to the browser interface. Rather than requiring separate applications or complex workflows, extensions provide immediate access to tools and features. This concept mirrors how early computer pioneers like Douglas Engelbart envisioned augmenting human capabilities with technology - extensions augment your browser's basic functionality. Popular extension categories and their benefits: - Productivity Tools: Task managers, note-taking apps, and time trackers that help you stay organized - Security Enhancements: Password managers, ad blockers, and privacy tools that protect your data - Developer Tools: Code formatters, color pickers, and debugging utilities that streamline development - Content Enhancement: Reading modes, video downloaders, and screenshot tools that improve your web experience ✅ Reflection Question: What are your favorite browser extensions? What specific tasks do they perform, and how do they improve your browsing experience? ### 🔄 Pedagogical Check-in Browser Architecture Understanding: Before moving to extension development, ensure you can: - ✅ Explain how browsers process web requests and render content - ✅ Identify the main components of browser architecture - ✅ Understand how extensions integrate with browser functionality - ✅ Recognize the security model that protects users Quick Self-Test: Can you trace the path from typing a URL to seeing a webpage? 1. DNS lookup converts URL to IP address 2. HTTP request fetches content from server 3. Parsing processes HTML, CSS, and JavaScript 4. Rendering displays the final webpage 5. Extensions can modify content at multiple steps ## Installing and Managing Extensions Understanding the extension installation process helps you anticipate the user experience when people install your extension. The installation process is standardized across modern browsers, with minor variations in interface design. ### Development Extension Installation Process When you're developing and testing your own extensions, follow this workflow: What this command accomplishes: - Compiles your source code into browser-ready files - Bundles JavaScript modules into optimized packages - Generates the final extension files in the /dist folder - Prepares your extension for installation and testing Step 2: Navigate to Browser Extensions 1. Open your browser's extensions management page 2. Click the "Settings and more" button (the ... icon) on the top right 3. Select "Extensions" from the dropdown menu Step 3: Load Your Extension - For new installations: Choose load unpacked and select your /dist folder - For updates: Click reload next to your already-installed extension - For testing: Enable "Developer mode" to access additional debugging features ### Production Extension Installation Understanding the difference: - Development installations let you test unpublished extensions during development - Store installations provide vetted, published extensions with automatic updates - Sideloading allows installation of extensions from outside official stores (requires developer mode) ## Building Your Carbon Footprint Extension We'll create a browser extension that displays the carbon footprint of your region's energy use. This project demonstrates essential extension development concepts while creating a practical tool for environmental awareness. This approach follows the principle of "learning by doing" that has proven effective since John Dewey's educational theories - combining technical skills with meaningful real-world applications. ### Project Requirements Before beginning development, let's gather the required resources and dependencies: Required API Access: - CO2 Signal API key: Enter your email address to receive your free API key - Region code: Find your region code using the Electricity Map (for example, Boston uses 'US-NEISO') Development Tools: - Node.js and NPM: Package management tool for installing project dependencies - Starter code: Download the start folder to begin development ✅ Learn More: Enhance your package management skills with this comprehensive Learn module ### Understanding the Project Structure Understanding the project structure helps organize development work efficiently. Like how the Library of Alexandria was organized for easy knowledge retrieval, a well-structured codebase makes development more efficient: Breaking down what each file accomplishes: - manifest.json: Defines extension metadata, permissions, and entry points - index.html: Creates the user interface that appears when users click your extension - background.js: Handles background tasks and browser event listeners - main.js: Contains the final bundled JavaScript after the build process - src/index.js: Houses your main development code that gets compiled into main.js ✅ Security Note: Never commit API keys or sensitive credentials to your code repository. We'll show you how to handle these securely in the next steps. ## Creating the Extension Interface Now we'll build the user interface components. The extension uses a two-screen approach: a configuration screen for initial setup and a results screen for data display. This follows the progressive disclosure principle used in interface design since the early days of computing - revealing information and options in a logical sequence to avoid overwhelming users. ### Extension Views Overview Setup View - First-time user configuration: Results View - Carbon footprint data display: ### Building the Configuration Form The setup form collects user configuration data during initial use. Once configured, this information persists in browser storage for future sessions. In the /dist/index.html file, add this form structure: Here's what this form accomplishes: - Creates a semantic form structure with proper labels and input associations - Enables browser autocomplete functionality for improved user experience - Requires both fields to be filled before submission using the required attribute - Organizes inputs with descriptive class names for easy styling and JavaScript targeting - Provides clear instructions for users who are setting up the extension for the first time ### Building the Results Display Next, create the results area that will show the carbon footprint data. Add this HTML below the form: Breaking down what this structure provides: - loading: Displays a loading message while API data is being fetched - errors: Shows error messages if API calls fail or data is invalid - data: Holds raw data for debugging purposes during development - result-container: Presents formatted carbon footprint information to users - clear-btn: Allows users to change their region and reconfigure the extension ### Setting Up the Build Process Now let's install the project dependencies and test the build process: What this installation process accomplishes: - Downloads Webpack and other development dependencies specified in package.json - Configures the build toolchain for compiling modern JavaScript - Prepares the development environment for extension building and testing - Enables code bundling, optimization, and cross-browser compatibility features ### Testing Your Progress At this point, you can test your extension: 1. Run the build command to compile your code 2. Load the extension into your browser using the developer mode 3. Verify that the form displays correctly and looks professional 4. Check that all form elements are properly aligned and functional What you've accomplished: - Built the foundational HTML structure for your extension - Created both configuration and results interfaces with proper semantic markup - Set up a modern development workflow using industry-standard tools - Prepared the foundation for adding interactive JavaScript functionality ### 🔄 Pedagogical Check-in Extension Development Progress: Verify your understanding before continuing: - ✅ Can you explain the purpose of each file in the project structure? - ✅ Do you understand how the build process transforms your source code? - ✅ Why do we separate configuration and results into different UI sections? - ✅ How does the form structure support both usability and accessibility? Development Workflow Understanding: You should now be able to: 1. Modify HTML and CSS for your extension interface 2. Run the build command to compile your changes 3. Reload the extension in your browser to test updates 4. Debug issues using browser developer tools You've completed the first phase of browser extension development. Like how the Wright brothers first needed to understand aerodynamics before achieving flight, understanding these foundational concepts prepares you for building more complex interactive features in the next lesson. ## GitHub Copilot Agent Challenge 🚀 Use the Agent mode to complete the following challenge: Description: Enhance the browser extension by adding form validation and user feedback features to improve the user experience when entering API keys and region codes. Prompt: Create JavaScript validation functions that check if the API key field contains at least 20 characters and if the region code follows the correct format (like 'US-NEISO'). Add visual feedback by changing input border colors to green for valid inputs and red for invalid ones. Also add a toggle feature to show/hide the API key for security purposes. Learn more about agent mode here. ## 🚀 Challenge Take a look at a browser extension store and install one to your browser. You can examine its files in interesting ways. What do you discover? ## Post-Lecture Quiz Post-lecture quiz ## Review & Self Study In this lesson you learned a little about the history of the web browser; take this opportunity to learn about how the inventors of the World Wide Web envisioned its use by reading more about its history. Some useful sites include: The History of Web Browsers History of the Web An interview with Tim Berners-Lee ### ⚡ What You Can Do in the Next 5 Minutes - [ ] Open Chrome/Edge extensions page (chrome://extensions) and explore what you have installed - [ ] Look at your browser's DevTools Network tab while loading a webpage - [ ] Try viewing page source (Ctrl+U) to see HTML structure - [ ] Inspect any webpage element and modify its CSS in DevTools ### 🎯 What You Can Accomplish This Hour - [ ] Complete the post-lesson quiz and understand browser fundamentals - [ ] Create a basic manifest.json file for a browser extension - [ ] Build a simple "Hello World" extension that shows a popup - [ ] Test loading your extension in developer mode - [ ] Explore the browser extension documentation for your target browser ### 📅 Your Week-Long Extension Journey - [ ] Complete a functional browser extension with real utility - [ ] Learn about content scripts, background scripts, and popup interactions - [ ] Master browser APIs like storage, tabs, and messaging - [ ] Design user-friendly interfaces for your extension - [ ] Test your extension across different websites and scenarios - [ ] Publish your extension to the browser's extension store ### 🌟 Your Month-Long Browser Development - [ ] Build multiple extensions solving different user problems - [ ] Learn advanced browser APIs and security best practices - [ ] Contribute to open source browser extension projects - [ ] Master cross-browser compatibility and progressive enhancement - [ ] Create extension development tools and templates for others - [ ] Become a browser extension expert who helps other developers ## 🎯 Your Browser Extension Mastery Timeline ### 🛠️ Your Extension Development Toolkit Summary After completing this lesson, you now have: - Browser Architecture Knowledge: Understanding of rendering engines, security models, and extension integration - Development Environment: Modern toolchain with Webpack, NPM, and debugging capabilities - UI/UX Foundation: Semantic HTML structure with progressive disclosure patterns - Security Awareness: Understanding of browser permissions and safe development practices - Cross-Browser Concepts: Knowledge of compatibility considerations and testing approaches - API Integration: Foundation for working with external data sources - Professional Workflow: Industry-standard development and testing procedures Real-World Applications: These skills directly apply to: - Web Development: Single-page applications and progressive web apps - Desktop Applications: Electron and web-based desktop software - Mobile Development: Hybrid apps and web-based mobile solutions - Enterprise Tools: Internal productivity applications and workflow automation - Open Source: Contributing to browser extension projects and web standards Next Level: You're ready to add interactive functionality, work with browser APIs, and create extensions that solve real user problems! ## Assignment Restyle your extension

web,development

Browser Extension Project Part 2: Call an API, use Local Storage

## Pre-Lecture Quiz Pre-lecture quiz ## Introduction Remember that browser extension you started building? Right now you've got a nice-looking form, but it's essentially static. Today we'll bring it to life by connecting it to real data and giving it memory. Think about the Apollo mission control computers - they didn't just display fixed information. They constantly communicated with spacecraft, updated with telemetry data, and remembered critical mission parameters. That's the kind of dynamic behavior we're building today. Your extension will reach out to the internet, grab real environmental data, and remember your settings for next time. API integration might sound complex, but it's really just teaching your code how to communicate with other services. Whether you're fetching weather data, social media feeds, or carbon footprint information like we'll do today, it's all about establishing these digital connections. We'll also explore how browsers can persist information - similar to how libraries have used card catalogs to remember where books belong. By the end of this lesson, you'll have a browser extension that fetches real data, stores user preferences, and provides a smooth experience. Let's get started! ✅ Follow the numbered segments in the appropriate files to know where to place your code ## Set up the elements to manipulate in the extension Before your JavaScript can manipulate the interface, it needs references to specific HTML elements. Think of it like a telescope needing to be pointed at particular stars - before Galileo could study Jupiter's moons, he had to locate and focus on Jupiter itself. In your index.js file, we'll create const variables that capture references to each important form element. This is similar to how scientists label their equipment - instead of searching through the entire laboratory each time, they can directly access what they need. Here's what this code does: - Captures form elements using document.querySelector() with CSS class selectors - Creates references to input fields for the region name and API key - Establishes connections to result display elements for carbon usage data - Sets up access to UI elements like loading indicators and error messages - Stores each element reference in a const variable for easy reuse throughout your code ## Add event listeners Now we'll make your extension respond to user actions. Event listeners are your code's way of monitoring user interactions. Think of them like the operators in early telephone exchanges - they listened for incoming calls and connected the right circuits when someone wanted to make a connection. Understanding these concepts: - Attaches a submit listener to the form that triggers when users press Enter or click submit - Connects a click listener to the clear button for resetting the form - Passes the event object (e) to handler functions for additional control - Calls the init() function immediately to set up the initial state of your extension ✅ Notice the shorthand arrow function syntax used here. This modern JavaScript approach is cleaner than traditional function expressions, but both work equally well! ### 🔄 Pedagogical Check-in Event Handling Understanding: Before moving to initialization, ensure you can: - ✅ Explain how addEventListener connects user actions to JavaScript functions - ✅ Understand why we pass the event object (e) to handler functions - ✅ Recognize the difference between submit and click events - ✅ Describe when the init() function runs and why Quick Self-Test: What would happen if you forgot e.preventDefault() in a form submission? Answer: The page would reload, losing all JavaScript state and interrupting the user experience ## Build the initialization and reset functions Let's create the initialization logic for your extension. The init() function is like a ship's navigation system checking its instruments - it determines the current state and adjusts the interface accordingly. It checks if someone has used your extension before and loads their previous settings. The reset() function provides users with a fresh start - similar to how scientists reset their instruments between experiments to ensure clean data. Breaking down what happens here: - Retrieves stored API key and region from browser's local storage - Checks if this is a first-time user (no stored credentials) or returning user - Shows the setup form for new users and hides other interface elements - Loads saved data automatically for returning users and displays the reset option - Manages the user interface state based on available data Key concepts about Local Storage: - Persists data between browser sessions (unlike session storage) - Stores data as key-value pairs using getItem() and setItem() - Returns null when no data exists for a given key - Provides a simple way to remember user preferences and settings You can view your stored data by opening browser Developer Tools (F12), navigating to the Application tab, and expanding the Local Storage section. ## Handle form submission Now we'll handle what happens when someone submits your form. By default, browsers reload the page when forms are submitted, but we'll intercept this behavior to create a smoother experience. This approach mirrors how mission control handles spacecraft communications - instead of resetting the entire system for each transmission, they maintain continuous operation while processing new information. Create a function that captures the form submission event and extracts the user's input: In the above, we've: - Prevents the default form submission behavior that would refresh the page - Extracts user input values from the API key and region fields - Passes the form data to the setUpUser() function for processing - Maintains single-page application behavior by avoiding page reloads ✅ Remember that your HTML form fields include the required attribute, so the browser automatically validates that users provide both the API key and region before this function runs. ## Set up user preferences The setUpUser function is responsible for saving the user's credentials and initiating the first API call. This creates a smooth transition from setup to displaying results. Step by step, here's what's happening: - Saves the API key and region name to local storage for future use - Shows a loading indicator to inform users that data is being fetched - Clears any previous error messages from the display - Reveals the clear button for users to reset their settings later - Initiates the API call to fetch real carbon usage data This function creates a seamless user experience by managing both data persistence and user interface updates in one coordinated action. ## Display carbon usage data Now we'll connect your extension to external data sources through APIs. This transforms your extension from a standalone tool into something that can access real-time information from across the internet. Understanding APIs APIs are how different applications communicate with each other. Think of them like the telegraph system that connected distant cities in the 19th century - operators would send requests to distant stations and receive responses with the requested information. Every time you check social media, ask a voice assistant a question, or use a delivery app, APIs are facilitating these data exchanges. Key concepts about REST APIs: - REST stands for 'Representational State Transfer' - Uses standard HTTP methods (GET, POST, PUT, DELETE) to interact with data - Returns data in predictable formats, typically JSON - Provides consistent, URL-based endpoints for different types of requests ✅ The CO2 Signal API we'll use provides real-time carbon intensity data from electrical grids worldwide. This helps users understand the environmental impact of their electricity usage! Here's a quick video about async: [](https://youtube.com/watch?v=YwmlRkrxvkk "Async and Await for managing promises") ### 🔄 Pedagogical Check-in Async Programming Understanding: Before diving into the API function, verify you understand: - ✅ Why we use async/await instead of blocking the entire extension - ✅ How try/catch blocks handle network errors gracefully - ✅ The difference between synchronous and asynchronous operations - ✅ Why API calls can fail and how to handle those failures Real-World Connection: Consider these everyday async examples: - Ordering food: You don't wait by the kitchen - you get a receipt and continue other activities - Sending emails: Your email app doesn't freeze while sending - you can compose more emails - Loading web pages: Images load progressively while you can already read the text API Authentication Flow: Create the function to fetch and display carbon usage data: Breaking down what happens here: - Uses the modern fetch() API instead of external libraries like Axios for cleaner, dependency-free code - Implements proper error checking with response.ok to catch API failures early - Handles asynchronous operations with async/await for more readable code flow - Authenticates with the CO2 Signal API using the auth-token header - Parses JSON response data and extracts carbon intensity information - Updates multiple UI elements with formatted environmental data - Provides user-friendly error messages when API calls fail Key modern JavaScript concepts demonstrated: - Template literals with ${} syntax for clean string formatting - Error handling with try/catch blocks for robust applications - Async/await pattern for handling network requests gracefully - Object destructuring to extract specific data from API responses - Method chaining for multiple DOM manipulations ✅ This function demonstrates several important web development concepts - communicating with external servers, handling authentication, processing data, updating interfaces, and managing errors gracefully. These are fundamental skills that professional developers use regularly. ### 🔄 Pedagogical Check-in Complete System Understanding: Verify your mastery of the entire flow: - ✅ How DOM references enable JavaScript to control the interface - ✅ Why local storage creates persistence between browser sessions - ✅ How async/await makes API calls without freezing the extension - ✅ What happens when API calls fail and how errors are handled - ✅ Why user experience includes loading states and error messages 🎉 What you've accomplished: You've created a browser extension that: - Connects to the internet and retrieves real environmental data - Persists user settings between sessions - Handles errors gracefully instead of crashing - Provides a smooth, professional user experience Test your work by running npm run build and refreshing your extension in the browser. You now have a functional carbon footprint tracker. The next lesson will add dynamic icon functionality to complete the extension. --- ## GitHub Copilot Agent Challenge 🚀 Use the Agent mode to complete the following challenge: Description: Enhance the browser extension by adding error handling improvements and user experience features. This challenge will help you practice working with APIs, local storage, and DOM manipulation using modern JavaScript patterns. Prompt: Create an enhanced version of the displayCarbonUsage function that includes: 1) A retry mechanism for failed API calls with exponential backoff, 2) Input validation for the region code before making the API call, 3) A loading animation with progress indicators, 4) Caching of API responses in localStorage with expiration timestamps (cache for 30 minutes), and 5) A feature to display historical data from previous API calls. Also add proper TypeScript-style JSDoc comments to document all function parameters and return types. Learn more about agent mode here. ## 🚀 Challenge Expand your understanding of APIs by exploring the wealth of browser-based APIs available for web development. Choose one of these browser APIs and build a small demonstration: - Geolocation API - Get user's current location - Notification API - Send desktop notifications - HTML Drag and Drop API - Create interactive drag interfaces - Web Storage API - Advanced local storage techniques - Fetch API - Modern alternative to XMLHttpRequest Research questions to consider: - What real-world problems does this API solve? - How does the API handle errors and edge cases? - What security considerations exist when using this API? - How widely supported is this API across different browsers? After your research, identify what characteristics make an API developer-friendly and reliable. ## Post-Lecture Quiz Post-lecture quiz ## Review & Self Study You learned about LocalStorage and APIs in this lesson, both very useful for the professional web developer. Can you think about how these two things work together? Think about how you would architect a web site that would store items to be used by an API. ### ⚡ What You Can Do in the Next 5 Minutes - [ ] Open DevTools Application tab and explore localStorage on any website - [ ] Create a simple HTML form and test form validation in the browser - [ ] Try storing and retrieving data using localStorage in the browser console - [ ] Inspect form data being submitted using the Network tab ### 🎯 What You Can Accomplish This Hour - [ ] Complete the post-lesson quiz and understand form handling concepts - [ ] Build a browser extension form that saves user preferences - [ ] Implement client-side form validation with helpful error messages - [ ] Practice using the chrome.storage API for extension data persistence - [ ] Create a user interface that responds to saved user settings ### 📅 Your Week-Long Extension Building - [ ] Complete a full-featured browser extension with form functionality - [ ] Master different storage options: local, sync, and session storage - [ ] Implement advanced form features like autocomplete and validation - [ ] Add import/export functionality for user data - [ ] Test your extension thoroughly across different browsers - [ ] Polish your extension's user experience and error handling ### 🌟 Your Month-Long Web API Mastery - [ ] Build complex applications using various browser storage APIs - [ ] Learn about offline-first development patterns - [ ] Contribute to open source projects involving data persistence - [ ] Master privacy-focused development and GDPR compliance - [ ] Create reusable libraries for form handling and data management - [ ] Share knowledge about web APIs and extension development ## 🎯 Your Extension Development Mastery Timeline ### 🛠️ Your Full-Stack Development Toolkit Summary After completing this lesson, you now have: - DOM Mastery: Precise element targeting and manipulation - Storage Expertise: Persistent data management with localStorage - API Integration: Real-time data fetching and authentication - Async Programming: Non-blocking operations with modern JavaScript - Error Handling: Robust applications that gracefully handle failures - User Experience: Loading states, validation, and smooth interactions - Modern Patterns: fetch API, async/await, and ES6+ features Professional Skills Gained: You've implemented patterns used in: - Web Applications: Single-page apps with external data sources - Mobile Development: API-driven apps with offline capabilities - Desktop Software: Electron apps with persistent storage - Enterprise Systems: Authentication, caching, and error handling - Modern Frameworks: React/Vue/Angular data management patterns Next Level: You're ready to explore advanced topics like caching strategies, real-time WebSocket connections, or complex state management! ## Assignment Adopt an API

api

Browser Extension Project Part 3: Learn about Background Tasks and Performance

Ever wonder what makes some browser extensions feel snappy and responsive while others seem sluggish? The secret lies in what's happening behind the scenes. While users click around your extension's interface, there's a whole world of background processes quietly managing data fetching, icon updates, and system resources. This is our final lesson in the browser extension series, and we're going to make your carbon footprint tracker work smoothly. You'll add dynamic icon updates and learn how to spot performance issues before they become problems. It's like tuning a race car - small optimizations can make a huge difference in how everything runs. By the time we're done, you'll have a polished extension and understand the performance principles that separate good web apps from great ones. Let's dive into the world of browser optimization. ## Pre-Lecture Quiz Pre-lecture quiz ### Introduction In our previous lessons, you built a form, connected it to an API, and tackled asynchronous data fetching. Your extension is taking shape nicely. Now we need to add the finishing touches - like making that extension icon change colors based on the carbon data. This reminds me of how NASA had to optimize every system on the Apollo spacecraft. They couldn't afford any wasted cycles or memory because lives depended on performance. While our browser extension isn't quite that critical, the same principles apply - efficient code creates better user experiences. ## Web Performance Basics When your code runs efficiently, people can actually feel the difference. You know that moment when a page loads instantly or an animation flows smoothly? That's good performance at work. Performance isn't just about speed - it's about making web experiences that feel natural instead of clunky and frustrating. Back in the early days of computing, Grace Hopper famously kept a nanosecond (a piece of wire about a foot long) on her desk to show how far light travels in one billionth of a second. It was her way of explaining why every microsecond matters in computing. Let's explore the detective tools that help you figure out what's slowing things down. The topic of how to make your websites blazingly fast on all kinds of devices, for all kinds of users, in all kinds of situations, is unsurprisingly vast. Here are some points to keep in mind as you build either a standard web project or a browser extension. The first step in optimizing your site is understanding what's actually happening under the hood. Fortunately, your browser comes with powerful detective tools built right in. To open Developer Tools in Edge, click those three dots in the top right corner, then go to More Tools > Developer Tools. Or use the keyboard shortcut: Ctrl + Shift + I on Windows or Option + Command + I on Mac. Once you're there, click on the Performance tab - this is where you'll do your investigation. Here's your performance detective toolkit: - Open Developer Tools (you'll use these constantly as a developer!) - Head to the Performance tab - think of it as your web app's fitness tracker - Hit that Record button and watch your page in action - Study the results to spot what's slowing things down Let's try this out. Open a website (Microsoft.com works well for this) and click that 'Record' button. Now refresh the page and watch the profiler capture everything that happens. When you stop recording, you'll see a detailed breakdown of how the browser 'scripts', 'renders', and 'paints' the site. It reminds me of how mission control monitors every system during a rocket launch - you get real-time data on exactly what's happening and when. ✅ The Microsoft Documentation has tons more details if you want to dive deeper Select elements of the profile timeline to zoom in on events that happen while your page loads. Get a snapshot of your page's performance by selecting a part of the profile timeline and looking at the summary pane: Check the Event Log pane to see if any event took longer than 15 ms: ✅ Get to know your profiler! Open the developer tools on this site and see if there are any bottlenecks. What's the slowest-loading asset? The fastest? ## What to Look For When Profiling Running the profiler is just the beginning - the real skill is knowing what those colorful charts are actually telling you. Don't worry, you'll get the hang of reading them. Experienced developers have learned to spot the warning signs before they become full-blown problems. Let's talk about the usual suspects - the performance troublemakers that tend to sneak into web projects. Like how Marie Curie had to carefully monitor radiation levels in her lab, we need to watch for certain patterns that indicate trouble brewing. Catching these early will save you (and your users) a lot of frustration. Asset sizes: Websites have been getting "heavier" over the years, and a lot of that extra weight comes from images. It's like we've been stuffing more and more into our digital suitcases. ✅ Check out the Internet Archive to see how page sizes have grown over time - it's quite revealing. Here's how to keep your assets optimized: - Compress those images! Modern formats like WebP can cut file sizes dramatically - Serve the right image size for each device - no need to send huge desktop images to phones - Minify your CSS and JavaScript - every byte counts - Use lazy loading so images only download when users actually scroll to them DOM traversals: The browser has to build its Document Object Model based on the code you write, so it's in the interest of good page performance to keep your tags minimal, only using and styling what the page needs. To this point, excess CSS associated with a page could be optimized; styles that need to be used only on one page don't need to be included in the main style sheet, for example. Key strategies for DOM optimization: - Minimizes the number of HTML elements and nesting levels - Removes unused CSS rules and consolidates stylesheets efficiently - Organizes CSS to load only what's needed for each page - Structures HTML semantically for better browser parsing JavaScript: Every JavaScript developer should watch for 'render-blocking' scripts that must be loaded before the rest of the DOM can be traversed and painted to the browser. Consider using defer with your inline scripts (as is done in the Terrarium module). Modern JavaScript optimization techniques: - Uses the defer attribute to load scripts after DOM parsing - Implements code splitting to load only necessary JavaScript - Applies lazy loading for non-critical functionality - Minimizes the use of heavy libraries and frameworks when possible ✅ Try some sites on a Site Speed Test website to learn more about the common checks that are done to determine site performance. ### 🔄 Pedagogical Check-in Performance Understanding: Before building extension features, ensure you can: - ✅ Explain the critical rendering path from HTML to pixels - ✅ Identify common performance bottlenecks in web applications - ✅ Use browser developer tools to profile page performance - ✅ Understand how asset size and DOM complexity affect speed Quick Self-Test: What happens when you have render-blocking JavaScript? Answer: The browser must download and execute the script before it can continue parsing HTML and rendering the page Real-World Performance Impact: - 100ms delay: Users notice the slowdown - 1 second delay: Users start losing focus - 3+ seconds: 40% of users abandon the page - Mobile networks: Performance matters even more Now that you have an idea of how the browser renders the assets you send to it, let's look at the last few things you need to do to complete your extension: ### Create a function to calculate color Now we'll create a function that turns numerical data into meaningful colors. Think of it like a traffic light system - green for clean energy, red for high carbon intensity. This function will take the CO2 data from our API and determine what color best represents the environmental impact. It's similar to how scientists use color-coding in heat maps to visualize complex data patterns - from ocean temperatures to star formation. Let's add this to /src/index.js, right after those const variables we set up earlier: Let's break down this clever little function: - Sets up two arrays - one for CO2 levels, another for colors (green = clean, brown = dirty!) - Finds the closest match to our actual CO2 value using some neat array sorting - Grabs the matching color using the findIndex() method - Sends a message to Chrome's background script with our chosen color - Uses template literals (those backticks) for cleaner string formatting - Keeps everything organized with const declarations The chrome.runtime API is like the nervous system of your extension - it handles all the behind-the-scenes communication and tasks: Why the Chrome Runtime API is so handy: - Lets different parts of your extension talk to each other - Handles background work without freezing the user interface - Manages your extension's lifecycle events - Makes message passing between scripts super easy ✅ If you're developing this browser extension for Edge, it might surprise you that you're using a chrome API. The newer Edge browser versions run on the Chromium browser engine, so you can leverage these tools. ### Set a default icon color Before we start fetching real data, let's give our extension a starting point. Nobody likes staring at a blank or broken-looking icon. We'll start with a green color so users know the extension is working from the moment they install it. In your init() function, let's set up that default green icon: What this initialization accomplishes: - Sets a neutral green color as the default state - Provides immediate visual feedback when the extension loads - Establishes the communication pattern with the background script - Ensures users see a functional extension before data loads ### Call the function, execute the call Now let's connect everything together so that when fresh CO2 data comes in, your icon automatically updates with the right color. It's like connecting the final circuit in an electronic device - suddenly all the individual components work as one system. Add this line right after you get the CO2 data from the API: This integration accomplishes: - Connects the API data flow with the visual indicator system - Triggers icon updates automatically when new data arrives - Ensures real-time visual feedback based on current carbon intensity - Maintains the separation of concerns between data fetching and display logic And finally, in /dist/background.js, add the listener for these background action calls: Here's what this background script does: - Listens for messages from your main script (like a receptionist taking calls) - Processes those 'updateIcon' requests to change your toolbar icon - Creates new icons on the fly using the Canvas API - Draws a simple colored circle that shows the current carbon intensity - Updates your browser toolbar with the fresh icon - Uses OffscreenCanvas for smooth performance (no UI blocking) ✅ You'll learn more about the Canvas API in the Space Game lessons. ### 🔄 Pedagogical Check-in Complete Extension Understanding: Verify your mastery of the entire system: - ✅ How does message passing work between different extension scripts? - ✅ Why do we use OffscreenCanvas instead of regular Canvas for performance? - ✅ What role does the Chrome Runtime API play in extension architecture? - ✅ How does the color calculation algorithm map data to visual feedback? Performance Considerations: Your extension now demonstrates: - Efficient messaging: Clean communication between script contexts - Optimized rendering: OffscreenCanvas prevents UI blocking - Real-time updates: Dynamic icon changes based on live data - Memory management: Proper cleanup and resource handling Time to test your extension: - Build everything with npm run build - Reload your extension in the browser (don't forget this step) - Open your extension and watch that icon change colors - Check how it responds to real carbon data from around the world Now you'll know at a glance whether it's a good time for that load of laundry or if you should wait for cleaner energy. You've just built something genuinely useful and learned about browser performance along the way. ## GitHub Copilot Agent Challenge 🚀 Use the Agent mode to complete the following challenge: Description: Enhance the browser extension's performance monitoring capabilities by adding a feature that tracks and displays load times for different components of the extension. Prompt: Create a performance monitoring system for the browser extension that measures and logs the time it takes to fetch CO2 data from the API, calculate colors, and update the icon. Add a function called performanceTracker that uses the Performance API to measure these operations and displays the results in the browser console with timestamps and duration metrics. Learn more about agent mode here. ## 🚀 Challenge Here's an interesting detective mission: pick a few open source websites that have been around for years (think Wikipedia, GitHub, or Stack Overflow) and dig into their commit history. Can you spot where they made performance improvements? What problems kept cropping up? Your investigation approach: - Search commit messages for words like "optimize," "performance," or "faster" - Look for patterns - do they keep fixing the same types of issues? - Identify the common culprits that slow down websites - Share what you discover - other developers learn from real-world examples ## Post-Lecture Quiz Post-lecture quiz ## Review & Self Study Consider signing up for a performance newsletter Investigate some of the ways that browsers gauge web performance by looking through the performance tabs in their web tools. Do you find any major differences? ### ⚡ What You Can Do in the Next 5 Minutes - [ ] Open browser Task Manager (Shift+Esc in Chrome) to see extension resource usage - [ ] Use DevTools Performance tab to record and analyze webpage performance - [ ] Check the browser's Extensions page to see which extensions impact startup time - [ ] Try disabling extensions temporarily to see performance differences ### 🎯 What You Can Accomplish This Hour - [ ] Complete the post-lesson quiz and understand performance concepts - [ ] Implement a background script for your browser extension - [ ] Learn to use browser.alarms for efficient background tasks - [ ] Practice message passing between content scripts and background scripts - [ ] Measure and optimize your extension's resource usage ### 📅 Your Week-Long Performance Journey - [ ] Complete a high-performance browser extension with background functionality - [ ] Master service workers and modern extension architecture - [ ] Implement efficient data synchronization and caching strategies - [ ] Learn advanced debugging techniques for extension performance - [ ] Optimize your extension for both functionality and resource efficiency - [ ] Create comprehensive tests for extension performance scenarios ### 🌟 Your Month-Long Optimization Mastery - [ ] Build enterprise-grade browser extensions with optimal performance - [ ] Learn about Web Workers, Service Workers, and modern web performance - [ ] Contribute to open source projects focused on performance optimization - [ ] Master browser internals and advanced debugging techniques - [ ] Create performance monitoring tools and best practices guides - [ ] Become a performance expert who helps optimize web applications ## 🎯 Your Browser Extension Mastery Timeline ### 🛠️ Your Complete Extension Development Toolkit After completing this trilogy, you now have mastered: - Browser Architecture: Deep understanding of how extensions integrate with browser systems - Performance Profiling: Ability to identify and fix bottlenecks using developer tools - Async Programming: Modern JavaScript patterns for responsive, non-blocking operations - API Integration: External data fetching with authentication and error handling - Visual Design: Dynamic UI updates and Canvas-based graphics generation - Message Passing: Inter-script communication in extension architectures - User Experience: Loading states, error handling, and intuitive interactions - Production Skills: Testing, debugging, and optimization for real-world deployment Real-World Applications: Your extension development skills apply directly to: - Progressive Web Apps: Similar architecture and performance patterns - Electron Desktop Apps: Cross-platform applications using web technologies - Mobile Hybrid Apps: Cordova/PhoneGap development using web APIs - Enterprise Web Applications: Complex dashboard and productivity tools - Chrome DevTools Extensions: Advanced developer tooling and debugging - Web API Integration: Any application that communicates with external services Professional Impact: You can now: - Build production-ready browser extensions from concept to deployment - Optimize web application performance using industry-standard profiling tools - Architect scalable systems with proper separation of concerns - Debug complex async operations and cross-context communication - Contribute to open source extension projects and browser standards Next Level Opportunities: - Chrome Web Store Developer: Publish extensions for millions of users - Web Performance Engineer: Specialize in optimization and user experience - Browser Platform Developer: Contribute to browser engine development - Extension Framework Creator: Build tools that help other developers - Developer Relations: Share knowledge through teaching and content creation 🌟 Achievement Unlocked: You've built a complete, functional browser extension that demonstrates professional development practices and modern web standards! ## Assignment Analyze a site for performance

web,development

Carbon Trigger Browser Extension: Completed Code

Using tmrow's C02 Signal API to track electricity usage, build a browser extension so that you can have a reminder right in your browser about how heavy your region's electricity usage is. Using this extension ad hoc will help you to make judgement calls on your activities based on this information. ## Getting Started You will need to have npm installed. Download a copy of this code to a folder on your computer. Install all the required packages: Build the extension from webpack To install on Edge, use the 'three dot' menu on the top right corner of the browser to find the Extensions panel. From there, select 'Load Unpacked' to load a new extension. Open the 'dist' folder at the prompt and the extension will load. To use it, you will need an API key for CO2 Signal's API (get one here via email - enter your email in the box on this page) and the code for your region corresponding to the Electricity Map (in Boston, for example, I use 'US-NEISO'). Once the API key and region is input into the extension interface, the colored dot in the browser extension bar should change to reflect your region's energy usage and give you a pointer on what energy-heavy activities would be appropriate for you to perform. The concept behind this 'dot' system was given to me by the Energy Lollipop extension for California emissions.

web,development

Carbon Trigger Browser Extension: Starter Code

Using tmrow's C02 Signal API to track electricity usage, build a browser extension so that you can have a reminder right in your browser about how heavy your region's electricity usage is. Using this extension ad hoc will help you to make judgement calls on your activities based on this information. ## Getting Started You will need to have npm installed. Download a copy of this code to a folder on your computer. Install all the required packages: Build the extension from webpack To install on Edge, use the 'three dot' menu on the top right corner of the browser to find the Extensions panel. From there, select 'Load Unpacked' to load a new extension. Open the 'dist' folder at the prompt and the extension will load. To use it, you will need an API key for CO2 Signal's API (get one here via email - enter your email in the box on this page) and the code for your region corresponding to the Electricity Map (in Boston, for example, I use 'US-NEISO'). Once the API key and region is input into the extension interface, the colored dot in the browser extension bar should change to reflect your region's energy usage and give you a pointer on what energy-heavy activities would be appropriate for you to perform. The concept behind this 'dot' system was given to me by the Energy Lollipop extension for California emissions.

web,development
Back to Home