folder names

This commit is contained in:
Jen Looper
2020-11-09 22:51:04 -05:00
parent 33e5d5f777
commit 1d81829ac1
367 changed files with 0 additions and 0 deletions

BIN
5-browser-extension/.DS_Store vendored Normal file

Binary file not shown.

View File

@@ -0,0 +1,18 @@
*Complete this quiz by checking one answer per question.*
1. The World Wide Web was invented by
- [ ] Tom Barnard-Loft
- [ ] Tim Berners-Lee
- [ ] Trish Berth-Pool
2. The first browser was called
- [ ] World Wide Web
- [ ] Mozilla
- [ ] Netscape
3. Browsers can store a user's browsing history
- [ ] true
- [ ] false

View File

@@ -0,0 +1,20 @@
*A warm-up quiz about browsers*
Complete this quiz in class
1. You can get browser extensions from
- [ ] WalMart
- [ ] The browser's extension store
- [ ] The App store
2. NPM stands for
- [ ] Node Package Manager
- [ ] Netscape Primary Mix
- [ ] Natural Processing Manager
3. Your browser can serve web pages both securely and insecurely
- [ ] true
- [ ] false

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 WebDev-For-Beginners
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,164 @@
# Browser Extension Project Part 1: All about Browsers
![Browser sketchnote](images/sketchnote.jpg)
> Sketchnote by [Wassim Chegham](https://dev.to/wassimchegham/ever-wondered-what-happens-when-you-type-in-a-url-in-an-address-bar-in-a-browser-3dob)
## [Pre-lecture quiz](.github/pre-lecture-quiz.md)
### Introduction:
Browser extensions add additional functionality to a browser. But before you build one, you should learn a little about how browsers do their work.
### About the browser:
In this series of lessons, you'll learn how to build a browser extension that will work on Chrome, Firefox and Edge browsers. In this part, you'll discover how browsers work and scaffold out the elements of the browser extension.
But what is a browser exactly? It is a software application that allows an end user to access content from a server and display it on web pages.
✅ A little history: the first browser was called 'WorldWideWeb' and was created by Sir Tim Berners-Lee in 1990.
![early browsers](images/earlybrowsers.jpg)
> Some early browsers, via [Karen McGrane](https://www.slideshare.net/KMcGrane/week-4-ixd-history-personal-computing)
When a user connected to the internet using a URL (Uniform Resource Locator) address, usually using Hypertext Transfer Protocol via an `http` or `https` address, the browser communicates with a web server and fetches a web page.
At this point, the browser's rendering engine displays it on the user's device, which might be a mobile phone, desktop, or laptop.
Browsers also have the ability to cache content so that it doesn't have to be retrieved from the server every time. They can record the history of a user's browsing activity, store 'cookies', which are small bits of data that contain information used to store a user's activity, and more.
A really important thing to remember about browsers is that they are not all the same! Each browser has its strengths and weaknesses, and a professional web developer needs to understand how to make web pages perform well cross-browser. This includes handling small viewports such as a mobile phone's, as well as a user who is offline.
A really useful website that you probably should bookmark in whatever browser you prefer to use is [caniuse.com](https://www.caniuse.com). When you are building web pages, it's very helpful to use caniuse's lists of supported technologies so that you can best support your users.
✅ How can you tell what browsers are most popular with your web site's user base? Check your analytics - you can install various analytics packages as part of your web development process, and they will tell you what browsers are most used by the various popular browsers.
## Browser extensions
Why would you want to build a browser extension? It's a handy thing to attach to your browser when you need quick access to tasks that you tend to repeat. For example, if you find yourself needing to check colors on the various web pages that you interact with, you might install a color-picker browser extension. If you have trouble remembering passwords, you might use a password-management browser extension.
Browser extensions are fun to develop, too. They tend to manage a finite number of tasks that they perform well.
✅ What are your favorite browser extensions? What tasks do they perform?
### Installing extensions
Before you start building, take a look at the process of building and deploying a browser extension. While each browser varies a bit in how they manage this task, the process is similar on Chrome and Firefox to this example on Edge:
![install a browser extension](images/install-on-edge.png)
In essence, the process will be:
- build your extension using `npm build`
- navigate in the browser to the extensions pane using the `...` icon on the top right
- if it's a new installation, choose `load unpacked` to upload a fresh extension from its build folder (in our case it is `/dist`)
- or, click `reload` if you are reloading the already-installed extension
✅ These instructions pertain to extensions you build yourself; to install extensions that have been released to the browser extension store associated to each browser, you should navigate to those [stores](https://microsoftedge.microsoft.com/addons/Microsoft-Edge-Extensions-Home) and install the extension of your choice.
### Get Started
You're going to build a browser extension that displays your region's carbon footprint, showing your region's energy usage and the source of the energy. The extension will have a form that collects an API key so that you can access
CO2 Signal's API.
**You need:**
- [an API key](https://www.co2signal.com/); enter your email in the box on this page and one will be sent to you
- the [code for your region](http://api.electricitymap.org/v3/zones) corresponding to the [Electricity Map](https://www.electricitymap.org/map) (in Boston, for example, I use 'US-NEISO').
- the [starter code](../start). Download the `start` folder; you will be completing code in this folder.
- [NPM](https://www.npmjs.com) - NPM is a package management tool; install it locally and the packages listed in you `package.json` file will be installed for use by your web asset
✅ Learn more about package management in this [excellent Learn module](https://docs.microsoft.com/en-us/learn/modules/create-nodejs-project-dependencies/)
Take a minute to look through the codebase:
dist
-|manifest.json (defaults set here)
-|index.html (front-end HTML markup here)
-|background.js (background JS here)
-|main.js (built JS)
src
-|index.js (your JS code goes here)
✅ Once you have your API key and Region code handy, store those somewhere in a note for future use.
### Build the HTML for the extension
This extension has two views. One to gather the API key and region code:
![extension form](images/1.png)
And the second to display the region's carbon usage:
![carbon usage](images/2.png)
Let's start by building the HTML for the form and styling it with CSS.
In the `/dist` folder, you will build a form and a result area. In the `index.html` file, populate the delineated form area:
```HTML
<form class="form-data" autocomplete="on">
<div>
<h2>New? Add your Information</h2>
</div>
<div>
<label>Region Name</label>
<input type="text" required class="region-name" />
</div>
<div>
<label>Your API Key from tmrow</label>
<input type="text" required class="api-key" />
</div>
<button class="search-btn">Submit</button>
</form>
```
This is the form where your saved information will be input and saved to local storage.
Next, create the results area; under the final form tag, add some divs:
```HTML
<div class="result">
<div class="loading">loading...</div>
<div class="errors"></div>
<div class="data"></div>
<div class="result-container">
<p><strong>Region: </strong><span class="my-region"></span></p>
<p><strong>Carbon Usage: </strong><span class="carbon-usage"></span></p>
<p><strong>Fossil Fuel Percentage: </strong><span class="fossil-fuel"></span></p>
</div>
<button class="clear-btn">Change region</button>
</div>
```
At this point, you can try a build. Make sure to install the package dependencies of this extension:
```
npm install
```
This command will use npm, the Node Package Manager, to install webpack for your extension's build process. Webpack is a bundler that handles compiling code. You can see the output of this process by looking in `/dist/main.js` - you see the code has been bundled.
For now, the extension should build and, if you deploy it into Edge as an extension, you'll see a form neatly displayed.
Congratulations, you've taken the first steps towards building a browser extension. In subsequent lessons, you'll make it more functional and useful.
---
## 🚀 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](.github/post-lecture-quiz.md)
## 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](https://www.mozilla.org/en-US/firefox/browsers/browser-history/)
[History of the Web](https://webfoundation.org/about/vision/history-of-the-web/)
[An interview with Tim Berners-Lee](https://www.theguardian.com/technology/2019/mar/12/tim-berners-lee-on-30-years-of-the-web-if-we-dream-a-little-we-can-get-the-web-we-want)
## Assignment
[Restyle your extension](assignment.md)

View File

@@ -0,0 +1,11 @@
# Restyle your Extension
## Instructions
The codebase for this extension comes complete with styles, but you don't have to use them; make your extension your own by restyling it by editing its css file.
## Rubric
| Criteria | Exemplary | Adequate | Needs Improvement |
| -------- | -------------------------------------------- | --------------------- | ----------------- |
| | Code is submitted with functional new styles | Styling is incomplete | Styles are buggy |

Binary file not shown.

After

Width:  |  Height:  |  Size: 322 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 319 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 181 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 147 KiB

View File

@@ -0,0 +1,161 @@
# Proyecto de extensión del navegador Parte 1: Todo sobre los navegadores
![Browser sketchnote](images/sketchnote.jpg)
> Sketchnote de [Wassim Chegham](https://dev.to/wassimchegham/ever-wondered-what-happens-when-you-type-in-a-url-in-an-address-bar-in-a-browser-3dob)
## [Pre-lecture prueba](.github/pre-lecture-quiz.md)
### Introducción:
Las extensiones de navegador agregan funcionalidad adicional a un navegador. Pero antes de crear uno, debe aprender un poco sobre cómo funcionan los navegadores.
### Acerca del navegador:
En esta serie de lecciones, aprenderá a crear una extensión de navegador que funcione en los navegadores Chrome, Firefox y Edge. En esta parte, descubrirá cómo funcionan los navegadores y distribuirá los elementos de la extensión del navegador.
Pero, ¿qué es exactamente un navegador? Es una aplicación de software que permite al usuario final acceder al contenido de un servidor y mostrarlo en páginas web.
✅ Un poco de historia: el primer navegador se llamó 'WorldWideWeb' y fue creado por Sir Tim Berners-Lee en 1990.
! [navegadores iniciales](images / earlybrowsers.jpg)
> Algunos de los primeros navegadores, a través de [Karen McGrane](https://www.slideshare.net/KMcGrane/week-4-ixd-history-personal-computing)
Cuando un usuario se conecta a Internet usando una dirección URL (Localizador uniforme de recursos), generalmente usando el Protocolo de transferencia de hipertexto a través de una dirección `http` o` https`, el navegador se comunica con un servidor web y busca una página web.
En este punto, el motor de renderizado del navegador lo muestra en el dispositivo del usuario, que puede ser un teléfono móvil, una computadora de escritorio o una computadora portátil.
Los navegadores también tienen la capacidad de almacenar en caché el contenido para que no sea necesario recuperarlo del servidor cada vez. Pueden registrar el historial de la actividad de navegación de un usuario, almacenar 'cookies', que son pequeños fragmentos de datos que contienen información que se utiliza para almacenar la actividad de un usuario, y más.
Una cosa realmente importante para recordar acerca de los navegadores es que no todos son iguales. Cada navegador tiene sus fortalezas y debilidades, y un desarrollador web profesional debe comprender cómo hacer que las páginas web funcionen bien en todos los navegadores. Esto incluye el manejo de pequeñas ventanas gráficas, como las de un teléfono móvil, así como de un usuario sin conexión.
Un sitio web realmente útil que probablemente debería marcar en cualquier navegador que prefiera usar es [caniuse.com](https://www.caniuse.com). Cuando está creando páginas web, es muy útil utilizar las listas de tecnologías compatibles de caniuse para que pueda ayudar mejor a sus usuarios.
✅ ¿Cómo puede saber qué navegadores son los más populares entre la base de usuarios de su sitio web? Verifique sus análisis: puede instalar varios paquetes de análisis como parte de su proceso de desarrollo web, y le dirán qué navegadores son los más utilizados por los diversos navegadores populares.
## Extensiones de navegador
¿Por qué querrías crear una extensión de navegador? Es muy útil adjuntarlo a su navegador cuando necesita acceso rápido a tareas que tiende a repetir. Por ejemplo, si necesita comprobar los colores en las distintas páginas web con las que interactúa, puede instalar una extensión de navegador de selector de color. Si tiene problemas para recordar las contraseñas, puede utilizar una extensión de navegador de administración de contraseñas.
Las extensiones de navegador también son divertidas de desarrollar. Suelen gestionar un número finito de tareas que realizan bien.
✅ ¿Cuáles son sus extensiones de navegador favoritas? ¿Qué tareas realizan?
### Instalando extensiones
Antes de empezar a crear, observe el proceso de creación e implementación de una extensión de navegador. Si bien cada navegador varía un poco en la forma en que administran esta tarea, el proceso es similar en Chrome y Firefox a este ejemplo en Edge:
![instalar una extensión de navegador](images/install-on-edge.png)
En esencia, el proceso será:
- construye tu extensión usando `npm build`
- navegue en el navegador hasta el panel de extensiones usando el icono `...` en la parte superior derecha
- si se trata de una nueva instalación, elija `load unpacked` para cargar una nueva extensión desde su carpeta de compilación (en nuestro caso es `/ dist`)
- o haga clic en `recargar` si está recargando la extensión ya instalada
✅ Estas instrucciones pertenecen a extensiones que usted mismo construye; para instalar extensiones que se han lanzado a la tienda de extensiones del navegador asociada a cada navegador, debe navegar a esas [tiendas](https://microsoftedge.microsoft.com/addons/Microsoft-Edge-Extensions-Home) e instalar la extensión de tu elección.
### Empezar
Vas a crear una extensión de navegador que muestre la huella de carbono de tu región, mostrando el uso de energía de tu región y la fuente de energía. La extensión tendrá un formulario que recopila una clave API para que pueda acceder
API de CO2 Signal.
**Necesitas:**
- [una clave API](https://www.co2signal.com/); ingrese su correo electrónico en el cuadro de esta página y se le enviará uno
- el [código de su región](http://api.electricitymap.org/v3/zones) correspondiente al [Mapa de electricidad](https://www.electricitymap.org/map) (en Boston, por ejemplo, Yo uso 'US-NEISO').
- el [código de inicio](../ inicio). Descargue la carpeta `start`; completará el código en esta carpeta.
- [NPM](https://www.npmjs.com) - NPM es una herramienta de gestión de paquetes; instálelo localmente y los paquetes enumerados en su archivo `package.json` se instalarán para que los use su recurso web
✅ Obtenga más información sobre la administración de paquetes en este [excelente módulo de aprendizaje](https://docs.microsoft.com/en-us/learn/modules/create-nodejs-project-dependencies/)
Tómate un minuto para revisar el código base:
dist
- | manifest.json (los valores predeterminados se establecen aquí)
- | index.html (marcado HTML de front-end aquí)
- | background.js (JS de fondo aquí)
- | main.js (JS construido)
src
- | index.js (su código JS va aquí)
✅ Una vez que tenga a mano su clave API y el código de región, guárdelos en algún lugar en una nota para uso futuro.
### Construye el HTML para la extensión
Esta extensión tiene dos vistas. Uno para recopilar la clave API y el código de región:
![extension form](1.png)
Y el segundo para mostrar el uso de carbono de la región:
![carbon usage](2.png)
Comencemos por construir el HTML para el formulario y darle estilo con CSS.
En la carpeta `/dist`, creará un formulario y un área de resultados. En el archivo `index.html`, complete el área delineada del formulario:
```HTML
<form class="form-data" autocomplete="on">
<div>
<h2>¿Nuevo? Agrega tu información</h2>
</div>
<div>
<label>Nombre de la región</label>
<input type="text" required class="region-name" />
</div>
<div>
<label>Tu clave API de tmrow</label>
<input type="text" required class="api-key" />
</div>
<button class="search-btn">Enviar</button>
</form>
```
Este es el formulario donde se ingresará la información guardada y se guardará en el almacenamiento local.
A continuación, cree el área de resultados; debajo de la etiqueta de formulario final, agregue algunos divs:
```HTML
<div class="result">
<div class="loading">cargando...</div>
<div class="errors"></div>
<div class="data"></div>
<div class="result-container">
<p><strong>Región: </strong><span class="my-region"></span></p>
<p><strong>Uso de carbono: </strong><span class="carbon-usage"></span></p>
<p><strong>Porcentaje de combustible fósil: </strong><span class="fossil-fuel"></span></p>
</div>
<button class="clear-btn">Cambia región</button>
</div>
```
En este punto, puede probar una compilación. Asegúrese de instalar las dependencias del paquete de esta extensión:
```
npm install
```
Este comando usará npm, el Node Package Manager, para instalar el paquete web para el proceso de compilación de su extensión. Webpack es un paquete que maneja la compilación de código. Puede ver el resultado de este proceso mirando en `/dist/main.js`; verá que el código se ha incluido.
Por ahora, la extensión debería compilarse y, si la implementa en Edge como una extensión, verá un formulario claramente mostrado.
Felicitaciones, ha dado los primeros pasos para crear una extensión de navegador. En lecciones posteriores, lo hará más funcional y útil.
🚀Challenge: Eche un vistazo a una tienda de extensiones de navegador e instale una en su navegador. Puede examinar sus archivos de formas interesantes. ¿Qué descubres?
## [Post-lecture prueba](.github/post-lecture-quiz.md)
## Revisión y autoestudio
En esta lección aprendió un poco sobre la historia del navegador web; Aproveche esta oportunidad para aprender cómo los inventores de la World Wide Web imaginaron su uso leyendo más sobre su historia. Algunos sitios útiles incluyen:
[La historia de los navegadores web](https://www.mozilla.org/en-US/firefox/browsers/browser-history/)
[Historia de la Web](https://webfoundation.org/about/vision/history-of-the-web/)
[Una entrevista con Tim Berners-Lee](https://www.theguardian.com/technology/2019/mar/12/tim-berners-lee-on-30-years-of-the-web-if-we-sueñe-un-poco-podemos-conseguir-la-web-que-queremos)
**Tarea**: [Cambia el estilo de tu extensión](assignment.md)

View File

@@ -0,0 +1,11 @@
# Cambia el estilo de tu extensión
## Instrucciones
El código base para esta extensión viene completo con estilos, pero no es necesario que los uses; haga suya su extensión al cambiarle el estilo editando su archivo css.
## Rúbrica
| Criterios | Ejemplar | Adecuado | Necesita mejorar |
| -------- | -------------------------------------------- | --------------------- | ----------------- |
| | El código se envía con nuevos estilos funcionales | El estilo está incompleto | Los estilos tienen errores |

View File

@@ -0,0 +1,16 @@
*Complete this quiz by checking one answer per question.*
1. LocalStorage is cleared every time you close the browser window
- [ ] true
- [ ] false
2. The main browser window controls a browser's extension's LocalStorage
- [ ] true
- [ ] false
3. REST in an API context stands for
- [ ] Representational State Transfer
- [ ] Returning State Tasks
- [ ] Rendering State To Browser

View File

@@ -0,0 +1,20 @@
*A warm-up quiz about the browser*
Complete this quiz in class
1. APIs stand for
- [ ] Application Programming Interfaces
- [ ] A Programming Inference
- [ ] Anti Proven Intentions
2. Use an API to interact with
- [ ] Another web-connected asset
- [ ] A database
- [ ] Either of the above
3. Anyone can create an API
- [ ] true
- [ ] false

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 WebDev-For-Beginners
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,218 @@
# Browser Extension Project Part 2: Call an API, use Local Storage
## [Pre-lecture quiz](.github/pre-lecture-quiz.md)
### Introduction:
In this lesson, you'll call an API by submitting your browser extension's form and display the results in your browser extension. In addition, you'll learn about how you can store data in your browser's local storage for future reference and use.
✅ Follow the numbered segments in the appropriate files to know where to place your code
### 1. Set up the elements to manipulate in the extension:
By this time you have built the HTML for the form and results `<div>` for your browser extension. From now on, you'll need to work in the `/src/index.js` file and building your extension bit by bit. Refer to the [previous lesson](../about-browsers/README.md) on getting your project set up and on the build process.
Working in your `index.js` file, start by creating some `const` variables to hold the values associated with various fields:
```JavaScript
// form fields
const form = document.querySelector('.form-data');
const region = document.querySelector('.region-name');
const apiKey = document.querySelector('.api-key');
// results
const errors = document.querySelector('.errors');
const loading = document.querySelector('.loading');
const results = document.querySelector('.result-container');
const usage = document.querySelector('.carbon-usage');
const fossilfuel = document.querySelector('.fossil-fuel');
const myregion = document.querySelector('.my-region');
const clearBtn = document.querySelector('.clear-btn');
```
All of these fields are referenced by their css class, as you set it up in the HTML in the previous lesson.
### 2. Add listeners
Next, add event listeners to the form and the clear button that resets the form, so that if a user submits the form or clicks that reset button, something will happen, and add the call to initialize the app at the bottom of the file:
```JavaScript
form.addEventListener('submit', (e) => handleSubmit(e));
clearBtn.addEventListener('click', (e) => reset(e));
init();
```
✅ Notice the shorthand used to listen for a submit or click event, and how the event it is passed to the handleSubmit or reset functions. Can you write the equivalent of this shorthand in a longer format? Which do you prefer?
### 3. Build out the init() function and the reset() function:
Now you are going to build the function that initializes the extension, which is called init():
```JavaScript
function init() {
//if anything is in localStorage, pick it up
const storedApiKey = localStorage.getItem('apiKey');
const storedRegion = localStorage.getItem('regionName');
//set icon to be generic green
//todo
if (storedApiKey === null || storedRegion === null) {
//if we don't have the keys, show the form
form.style.display = 'block';
results.style.display = 'none';
loading.style.display = 'none';
clearBtn.style.display = 'none';
errors.textContent = '';
} else {
//if we have saved keys/regions in localStorage, show results when they load
displayCarbonUsage(storedApiKey, storedRegion);
results.style.display = 'none';
form.style.display = 'none';
clearBtn.style.display = 'block';
}
};
function reset(e) {
e.preventDefault();
//clear local storage for region only
localStorage.removeItem('regionName');
init();
}
```
In this function, there is some interesting logic. Reading through it, can you see what happens?
- two `const` are set up to check if the user has stored an APIKey and region code in local storage.
- if either of those is null, show the form by changing its style to display as 'block'
- hide the results, loading, and clearBtn and set any error text to an empty string
- if there exists a key and region, start a routine to:
- call the API to get carbon usage data
- hide the results area
- hide the form
- show the reset button
Before moving on, it's useful to learn about a very important concept available in browsers: [LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage). LocalStorage is a useful way to store strings in the browser as a `key-value` pair. This type of web storage can be manipulated by JavaScript to manage data in the browser. LocalStorage does not expire, while SessionStorage, another kind of web storage, is cleared when the browser is closed. The various types of storage have pros and cons to their usage.
> Note - your browser extension has its own local storage; the main browser window is a different instance and behaves separately.
You set your APIKey to have a string value, for example, and you can see that it is set on Edge by "inspecting" a web page (you can right-click a browser to inspect) and going to the Applications tab to see the storage.
![Local storage pane](images/localstorage.png)
✅ Think about situations where you would NOT want to store some data in LocalStorage. In general, placing API Keys in LocalStorage is a bad idea! Can you see why? In our case, since our app is purely for learning and will not be deployed to an app store, we will use this method.
Notice that you use the Web API to manipulate LocalStorage, either by using `getItem()`, `setItem()` or `removeItem()`. It's widely supported across browsers.
Before building the `displayCarbonUsage()` function that is called in `init()`, let's build the functionality to handle the initial form submission.
### 4. Handle the form submission
Create a function called `handleSubmit` that accepts an event argument `(e)`. Stop the event from propagating (in this case, we want to stop the browser from refreshing) and call a new function, `setUpUser`, passing in the arguments `apiKey.value` and `region.value`. In this way, you use the two values that are brought in via the initial form when the appropriate fields are populated.
```JavaScript
function handleSubmit(e) {
e.preventDefault();
setUpUser(apiKey.value, region.value);
}
```
✅ Refresh your memory - the HTML you set up in the last lesson has two input fields whose `values` are captured via the `const` you set up at the top of the file, and they are both `required` so the browser stops users from inputting null values.
### 5. Set up the user
Moving on to the `setUpUser` function, here is where you set local storage values for apiKey and regionName. Add a new function:
```JavaScript
function setUpUser(apiKey, regionName) {
localStorage.setItem('apiKey', apiKey);
localStorage.setItem('regionName', regionName);
loading.style.display = 'block';
errors.textContent = '';
clearBtn.style.display = 'block';
//make initial call
displayCarbonUsage(apiKey, regionName);
}
```
This function sets a loading message to show while the API is called. At this point, you have arrived at creating the most important function of this browser extension!
### 6. Display Carbon Usage
Finally it's time to query the API!
Before going further, we should discuss APIs. APIs, or [Application Programming Interfaces](https://www.webopedia.com/TERM/A/API.html), are a critical element of a web developer's toolbox. They provide standard ways for programs to interact and interface with each other. For example, if you are building a web site that needs to query a database, someone might have created an API for you to use. While there are many types of APIs, one of the most popular is a [REST API](https://www.smashingmagazine.com/2018/01/understanding-using-rest-api/).
✅ The term 'REST' stands for 'Representational State Transfer' and features using variously-configured URLs to fetch data. Do a little research on the various types of APIs available to developers. What format appeals to you?
There are important things to note about this function. First notice the [`async` keyword](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). Writing your functions so that they run asynchronously means that they wait for an action, such as data being returned, to be completed before continuing.
Here's a quick video about `async`:
[![Async and Await for managing promises](https://img.youtube.com/vi/YwmlRkrxvkk/0.jpg)](https://youtube.com/watch?v=YwmlRkrxvkk "Async and Await for managing promises")
Create a new function to query the C02Signal API:
```JavaScript
import axios from '../node_modules/axios';
async function displayCarbonUsage(apiKey, region) {
try {
await axios
.get('https://api.co2signal.com/v1/latest', {
params: {
countryCode: region,
},
headers: {
'auth-token': apiKey,
},
})
.then((response) => {
let CO2 = Math.floor(response.data.data.carbonIntensity);
//calculateColor(CO2);
loading.style.display = 'none';
form.style.display = 'none';
myregion.textContent = region;
usage.textContent =
Math.round(response.data.data.carbonIntensity) + ' grams (grams C02 emitted per kilowatt hour)';
fossilfuel.textContent =
response.data.data.fossilFuelPercentage.toFixed(2) +
'% (percentage of fossil fuels used to generate electricity)';
results.style.display = 'block';
});
} catch (error) {
console.log(error);
loading.style.display = 'none';
results.style.display = 'none';
errors.textContent = 'Sorry, we have no data for the region you have requested.';
}
}
```
This is a big function. What's going on here?
- following best practices, you use an `async` keyword to make this function behave asyncronously. The function contains a `try/catch` block as it will return a promise when the API returns data. Because you don't have control over the speed that the API will respond (it may not respond at all!), you need to handle this uncertainty by call it asyncronously.
- you're querying the co2signal API to get your region's data, using your API Key. To use that key, you have to use a type of authentication in your header parameters.
- once the API responds, you assign various elements of its response data to the parts of your screen you set up to show this data.
- if there's an error, or if there is no result, you show an error message.
✅ Using asyncronous programming patterns is another very useful tool in your toolbox. Read [about the various ways](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) you can configure this type of code.
Congratulations! If you build your extension (`npm run build`) and refresh it in your extensions pane, you have a working extension! The only thing that isn't working is the icon, and you'll fix that in the next lesson.
---
## 🚀 Challenge
We've discussed several types of API so far in these lessons. Choose a web API and research in depth what it offers. For example, take a look at APIs available within browsers such as the [HTML Drag and Drop API](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API). What makes a great API in your opinion?
## [Post-lecture quiz](.github/post-lecture-quiz.md)
## Review & Self Study
You learned about LocalStorage and APIs in this lesson, both very useful for the professional web developer. Can you think 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.
## Assignment
[Adopt an API](assignment.md)

View File

@@ -0,0 +1,11 @@
# Adopt an API
## Instructions
APIs can be very fun to play with. Here is a [list of many free ones](https://github.com/public-apis/public-apis). Pick and API, and build a browser extension that solves a problem. It can be as small a problem of not having enough pet pictures (so, try the [dog CEO API](https://dog.ceo/dog-api/)) or something bigger - have fun!
## Rubric
| Criteria | Exemplary | Adequate | Needs Improvement |
| -------- | -------------------------------------------------------------------------- | ---------------------------------------- | ----------------------- |
| | A complete browser extension is submitted using an API from the above list | A partial browser extension is submitted | The submission has bugs |

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

View File

@@ -0,0 +1,212 @@
# Proyecto de extensión del navegador, parte 2: llamar a una API, usar almacenamiento local
## [Pre-lecture prueba](.github/pre-lecture-quiz.md)
### Introducción:
En esta lección, llamará a una API enviando el formulario de la extensión de su navegador y mostrará los resultados en la extensión de su navegador. Además, aprenderá cómo puede almacenar datos en el almacenamiento local de su navegador para referencia y uso futuros.
✅ Siga los segmentos numerados en los archivos correspondientes para saber dónde colocar su código
### 1. Configure los elementos para manipular en la extensión:
En este momento, ha creado el HTML para el formulario y los resultados `<div>` para la extensión de su navegador. De ahora en adelante, necesitará trabajar en el archivo `/src/index.js` y construir su extensión poco a poco. Consulte la [lección anterior](../about-browsers/ README.md) sobre cómo configurar su proyecto y el proceso de compilación.
Trabajando en su archivo `index.js`, comience creando algunas variables `const` para contener los valores asociados con varios campos:
```JavaScript
// form fields
const form = document.querySelector('.form-data');
const region = document.querySelector('.region-name');
const apiKey = document.querySelector('.api-key');
// results
const errors = document.querySelector('.errors');
const loading = document.querySelector('.loading');
const results = document.querySelector('.result-container');
const usage = document.querySelector('.carbon-usage');
const fossilfuel = document.querySelector('.fossil-fuel');
const myregion = document.querySelector('.my-region');
const clearBtn = document.querySelector('.clear-btn');
```
Todos estos campos están referenciados por su clase css, como lo configuró en el HTML en la lección anterior.
### 2. Agregar oyentes
A continuación, agregue detectores de eventos al formulario y el botón de borrar que restablece el formulario, de modo que si un usuario envía el formulario o hace clic en ese botón de restablecimiento, algo sucederá y agregue la llamada para inicializar la aplicación en la parte inferior del archivo:
```JavaScript
form.addEventListener('submit', (e) => handleSubmit(e));
clearBtn.addEventListener('click', (e) => reset(e));
init();
```
✅ Observe la abreviatura que se usa para escuchar un evento de envío o clic, y cómo el evento se pasa a las funciones handleSubmit o reset. ¿Puedes escribir el equivalente de esta abreviatura en un formato más largo? ¿Cual prefieres?
### 3. Desarrolle la init() y reset() función:
Ahora vas a construir la función que inicializa la extensión, que se llama `init()`:
```JavaScript
function init() {
//si hay algo en localStorage, recójalo
const storedApiKey = localStorage.getItem('apiKey');
const storedRegion = localStorage.getItem('regionName');
//establecer el icono en verde genérico
//todo
if (storedApiKey === null || storedRegion === null) {
//si no tenemos las claves, mostrar el formulario
form.style.display = 'block';
results.style.display = 'none';
loading.style.display = 'none';
clearBtn.style.display = 'none';
errors.textContent = '';
} else {
//si hemos guardado claves / regiones en localStorage, mostrar los resultados cuando se cargan
displayCarbonUsage(storedApiKey, storedRegion);
results.style.display = 'none';
form.style.display = 'none';
clearBtn.style.display = 'block';
}
};
function reset(e) {
e.preventDefault();
//borrar almacenamiento local solo para la región
localStorage.removeItem('regionName');
init();
}
```
En esta función, hay una lógica interesante. Al leerlo, ¿puedes ver lo que sucede?
- Se configuran dos `const` para verificar si el usuario ha almacenado una clave API y un código de región en el almacenamiento local.
- si alguno de ellos es nulo, muestre el formulario cambiando su estilo para que se muestre como 'bloque'
- ocultar los resultados, cargar y borrarBtn y establecer cualquier texto de error en una cadena vacía
- si existe una clave y una región, inicie una rutina para:
- llamar a la API para obtener datos de uso de carbono
- ocultar el área de resultados
- ocultar el formulario
- mostrar el botón de reinicio
Antes de continuar, es útil conocer un concepto muy importante disponible en los navegadores: [LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage). LocalStorage es una forma útil de almacenar cadenas en el navegador como un par "clave-valor". Este tipo de almacenamiento web puede ser manipulado por JavaScript para administrar datos en el navegador. LocalStorage no caduca, mientras que SessionStorage, otro tipo de almacenamiento web, se borra cuando se cierra el navegador. Los distintos tipos de almacenamiento tienen ventajas y desventajas para su uso.
> Nota: la extensión de su navegador tiene su propio almacenamiento local; la ventana principal del navegador es una instancia diferente y se comporta por separado.
Configura su APIKey para que tenga un valor de cadena, por ejemplo, y puede ver que está configurado en Edge "inspeccionando" una página web (puede hacer clic con el botón derecho en un navegador para inspeccionar) y yendo a la pestaña Aplicaciones para ver el almacenamiento.
![Panel de almacenamiento local](images/localstorage.png)
✅ Piense en situaciones en las que NO le gustaría almacenar algunos datos en LocalStorage. En general, colocar claves API en LocalStorage es una mala idea. ¿Puedes ver por qué? En nuestro caso, dado que nuestra aplicación es puramente para aprender y no se implementará en una tienda de aplicaciones, usaremos este método.
Tenga en cuenta que utiliza la API web para manipular LocalStorage, ya sea utilizando `getItem()`, `setItem()` o `removeItem()`. Es ampliamente compatible con todos los navegadores.
Antes de construir la función `displayCarbonUsage()` que se llama en `init()`, construyamos la funcionalidad para manejar el envío inicial del formulario.
### 4. Manejar el envío del formulario
Cree una función llamada `handleSubmit` que acepte un argumento de evento `(e)`. Detenga la propagación del evento (en este caso, queremos que el navegador no se actualice) y llame a una nueva función, `setUpUser`, pasando los argumentos `apiKey.value` y `region.value`. De esta manera, utiliza los dos valores que se introducen a través del formulario inicial cuando se completan los campos correspondientes.
```JavaScript
function handleSubmit(e) {
e.preventDefault();
setUpUser(apiKey.value, region.value);
}
```
✅ Refresque su memoria: el HTML que configuró en la última lección tiene dos campos de entrada cuyos `values` se capturan mediante la `const` que configuró en la parte superior del archivo, y ambos son `required` para que el navegador detenga a los usuarios de ingresar valores nulos.
### 5. Configurar el usuario
Pasando a la función `setUpUser`, aquí es donde configura los valores de almacenamiento local para apiKey y regionName. Agrega una nueva función:
```JavaScript
function setUpUser(apiKey, regionName) {
localStorage.setItem('apiKey', apiKey);
localStorage.setItem('regionName', regionName);
loading.style.display = 'block';
errors.textContent = '';
clearBtn.style.display = 'block';
//make initial call
displayCarbonUsage(apiKey, regionName);
}
```
Esta función establece un mensaje de carga para mostrar mientras se llama a la API. ¡En este punto, ha llegado a crear la función más importante de esta extensión de navegador!
### 6. Visualización del uso de carbono
¡Finalmente es hora de consultar la API!
Antes de continuar, deberíamos discutir las API. Las API, o [Interfaces de programación de aplicaciones](https://www.webopedia.com/TERM/A/API.html), son un elemento fundamental de la caja de herramientas de un desarrollador web. Proporcionan formas estándar para que los programas interactúen e interactúen entre sí. Por ejemplo, si está creando un sitio web que necesita consultar una base de datos, alguien podría haber creado una API para que la use. Si bien hay muchos tipos de API, una de las más populares es una [API REST](https://www.smashingmagazine.com/2018/01/understanding-using-rest-api/).
✅ El término 'REST' significa 'Transferencia de estado representacional' y características que utilizan URL configuradas de diversas formas para obtener datos. Investigue un poco sobre los distintos tipos de API disponibles para los desarrolladores. ¿Qué formato te atrae?
Hay cosas importantes a tener en cuenta sobre esta función. Primero observe la palabra clave `async`. Escribir sus funciones para que se ejecuten de forma asincrónica significa que
Cree una nueva función para consultar la API C02Signal:
```JavaScript
import axios from '../node_modules/axios';
async function displayCarbonUsage(apiKey, region) {
try {
await axios
.get('https://api.co2signal.com/v1/latest', {
params: {
countryCode: region,
},
headers: {
'auth-token': apiKey,
},
})
.then((response) => {
let CO2 = Math.floor(response.data.data.carbonIntensity);
//calculateColor(CO2);
loading.style.display = 'none';
form.style.display = 'none';
myregion.textContent = region;
usage.textContent =
Math.round(response.data.data.carbonIntensity) + ' grams (grams C02 emitted per kilowatt hour)';
fossilfuel.textContent =
response.data.data.fossilFuelPercentage.toFixed(2) +
'% (percentage of fossil fuels used to generate electricity)';
results.style.display = 'block';
});
} catch (error) {
console.log(error);
loading.style.display = 'none';
results.style.display = 'none';
errors.textContent = 'Sorry, we have no data for the region you have requested.';
}
}
```
Esta es una gran función. ¿Que está pasando aqui?
- siguiendo las mejores prácticas, utiliza una palabra clave `async` para hacer que esta función se comporte de forma asíncrona. La función contiene un bloque `try / catch` ya que devolverá una promesa cuando la API devuelva datos. Debido a que no tiene control sobre la velocidad a la que responderá la API (¡es posible que no responda en absoluto!), Debe manejar esta incertidumbre llamándola de forma asincrónica.
- está consultando la API co2signal para obtener los datos de su región, utilizando su clave API. Para usar esa clave, debe usar un tipo de autenticación en los parámetros de su encabezado.
- una vez que la API responde, asigna varios elementos de sus datos de respuesta a las partes de su pantalla que configura para mostrar estos datos.
- si hay un error o si no hay ningún resultado, muestra un mensaje de error.
✅ El uso de patrones de programación asíncronos es otra herramienta muy útil en su caja de herramientas. Lea [acerca de las diversas formas](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) puede configurar este tipo de código.
¡Felicidades! Si construye su extensión (`npm run build`) y la actualiza en su panel de extensiones, ¡tiene una extensión que funciona! Lo único que no funciona es el ícono, y lo solucionará en la próxima lección.
---
🚀 Desafío: hemos discutido varios tipos de API hasta ahora en estas lecciones. Elija una API web e investigue en profundidad lo que ofrece. Por ejemplo, eche un vistazo a las API disponibles en los navegadores, como la [API HTML de arrastrar y soltar] (https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API). En tu opinión, ¿qué hace que una API sea excelente?
## [Post-lecture prueba](.github/post-lecture-quiz.md)
## Revisión y autoestudio
Aprendió sobre LocalStorage y las API en esta lección, ambos muy útiles para el desarrollador web profesional. ¿Puedes pensar en cómo funcionan estas dos cosas juntas? Piense en cómo diseñaría un sitio web que almacenaría elementos para ser utilizados por una API.
**Tarea**: [Adopte una API](assignment.md)

View File

@@ -0,0 +1,11 @@
# Adopte una API
## Instrucciones
Puede ser muy divertido jugar con las API. Aquí hay una [lista de muchos gratuitos](https://github.com/public-apis/public-apis). Elija una API y cree una extensión de navegador que resuelva un problema. Puede ser un problema tan pequeño el no tener suficientes imágenes de mascotas (por lo tanto, pruebe la [API de CEO para perros](https://dog.ceo/dog-api/)) o algo más grande: ¡diviértase!
## Rúbrica
| Criterios | Ejemplar | Adecuado | Necesita mejorar |
| -------- | -------------------------------------------------- ------------------------ | ---------------------------------------- | ----------------------- |
| | Se envía una extensión de navegador completa utilizando una API de la lista anterior | Se envía una extensión de navegador parcial | La presentación tiene errores |

View File

@@ -0,0 +1,18 @@
*Complete this quiz by checking one answer per question.*
1. To get a better view of your site's performance, clear its cache and reload in the profiler
- [ ] true
- [ ] false
2. Browser extensions are inherently performant
- [ ] true
- [ ] false
3. Analyze the following for performance bottlenecks
- [ ] DOM traversals
- [ ] JavaScript optimizations
- [ ] Asset management
- [ ] All the above

View File

@@ -0,0 +1,18 @@
*Complete this quiz in class.*
1. Test the performance of your app
- [ ] Using the browser's tools
- [ ] Using a separate software package
- [ ] Manually
2. The 'performance' of a web site is an analysis of
- [ ] How fast it loads
- [ ] How fast the code on it runs
- [ ] Both of the above
3. Overall, the 'weight' of web pages over the past few years has gotten
- [ ] lighter
- [ ] heavier
- [ ] stayed the same

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 WebDev-For-Beginners
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,157 @@
# Browser Extension Project Part 3: Learn about Background Tasks and Performance
## [Pre-lecture quiz](.github/pre-lecture-quiz.md)
### Introduction:
In the last two lessons of this module, you learned how to build a form and display area for data fetched from an API. It's a very standard way of creating web presences on the web. You even learned how to handle fetching data asyncronously. Your browser extension is very nearly complete.
It remains to manage some background tasks, including refreshing the color of the extension's icon, so this is a great time to talk about how the browser manages this kind of task. Let's think about these browser tasks in the context of the performance of your web assets as you build them.
## Web Performance Basics
> "Website performance is about two things: how fast the page loads, and how fast the code on it runs." -- [Zack Grossbart](https://www.smashingmagazine.com/2012/06/javascript-profiling-chrome-developer-tools/)
The topic of how to make your web sites 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 thing you need to do to ensure that your site is running efficiently is to gather data about its performance. The first place to do this is in the developer tools of your web browser. In Edge, you can select the three dots on the top right of the browser, then navigate to More Tools > Developer Tools and open the Performance tab.
The Performance tab contains a Profiling tool. Open a web site (try, for example, https://www.microsoft.com) and click the 'Record' button, then refresh the site. Stop the recording at any time, and you will be able to see the routines that are generated to 'script', 'render', and 'paint' the site:
![Edge profiler](./images/profiler.png)
✅ Visit the [Microsoft Documentation](https://docs.microsoft.com/en-us/microsoft-edge/devtools-guide/performance) on the Performance panel in Edge
> Tip: to get a true reading of your web site's startup time, clear your browser's cache
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:
![Edge profiler snapshot](./images/snapshot.png)
Check the Event Log pane to see if any event took longer than 15 ms:
![Edge event log](./images/log.png)
✅ 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?
## Profiling checks
In general there are some "problem areas" that every web developer should watch for when building a site, so as to avoid nasty surprises when it's time to deploy to production.
**Asset sizes**: The web has gotten 'heavier', and thus slower, over the past few years. Some of this weight has to do with the use of images.
✅ Look through the [Internet Archive](https://httparchive.org/reports/page-weight) for a historical view of page weight and more.
A good practice is to ensure that your images are optimized, delivered at the right size and resolution for your users.
**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.
**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).
✅ Try some sites on a [Site Speed Test website](https://www.webpagetest.org/) to learn more about the common checks that are done to determine site performance.
Now that you have an idea on 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
Working in `/src/index.js`, add a function called `calculateColor()` after the series of `const` variables you set to gain access to the DOM:
```JavaScript
function calculateColor(value) {
let co2Scale = [0, 150, 600, 750, 800];
let colors = ['#2AA364', '#F5EB4D', '#9E4229', '#381D02', '#381D02'];
let closestNum = co2Scale.sort((a, b) => {
return Math.abs(a - value) - Math.abs(b - value);
})[0];
console.log(value + ' is closest to ' + closestNum);
let num = (element) => element > closestNum;
let scaleIndex = co2Scale.findIndex(num);
let closestColor = colors[scaleIndex];
console.log(scaleIndex, closestColor);
chrome.runtime.sendMessage({ action: 'updateIcon', value: { color: closestColor } });
}
```
What's going on here? You pass in a value (the carbon intensity) from the API call you completed in the last lesson, and then you calculate how close its value is to the index presented in colors array. Then you send that closest color value over to the chrome runtime.
The chrome.runtime has [an API](https://developer.chrome.com/extensions/runtime) that handles all kinds of background tasks, and your extension is leveraging that:
> "Use the chrome.runtime API to retrieve the background page, return details about the manifest, and listen for and respond to events in the app or extension lifecycle. You can also use this API to convert the relative path of URLs to fully-qualified URLs."
✅ 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.
> Note, if you want to profile a browser extension, launch the dev tools from within the extension itself, as it is its own separate browser instance.
### Set a default icon color
Now, in the `init()` function, set the icon to be generic green to start by again calling chrome's `updateIcon` action:
```JavaScript
chrome.runtime.sendMessage({
action: 'updateIcon',
value: {
color: 'green',
},
});
```
### Call the function, execute the call
Next, call that function you just created by adding it to the promise returned by the C02Signal API:
```JavaScript
//let CO2...
calculateColor(CO2);
```
And finally, in `/dist/background.js`, add the listener for these background action calls:
```JavaScript
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
if (msg.action === 'updateIcon') {
chrome.browserAction.setIcon({ imageData: drawIcon(msg.value) });
}
});
//borrowed from energy lollipop extension, nice feature!
function drawIcon(value) {
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
context.beginPath();
context.fillStyle = value.color;
context.arc(100, 100, 50, 0, 2 * Math.PI);
context.fill();
return context.getImageData(50, 50, 100, 100);
}
```
In this code, you are adding a listener for any messages coming to the backend task manager. If it's called 'updateIcon', then the next code is run, to draw an icon of the proper color using the Canvas API.
✅ You'll learn more about the Canvas API in the [Space Game lessons](../../space-game/drawing-to-canvas/README.md).
Now, rebuild your extension (`npm run build`), refresh and launch your extension, and watch the color change. Is it a good time to run an errand or wash the dishes? Now you know!
Congratulations, you've built a useful browser extension and learned more about how the browser works and how to profile its performance.
---
## 🚀 Challenge
Investigate some open source web sites have been around a long time ago, and, based on their GitHub history, see if you can determine how they were optimized over the years for performance, if at all. What is the most common pain point?
## [Post-lecture quiz](.github/post-lecture-quiz.md)
## Review & Self Study
Consider signing up for a [performance newsletter](https://perf.email/)
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?
## Assignment
[Analyze a site for performance](assignment.md)

View File

@@ -0,0 +1,9 @@
# Analyze a site for performance
Provide a detailed report of a web site, showing areas where performance is problematic. Analyze why the site is slow and what you could do to speed it up. Don't rely only on the browser tools, but do some research on other tools that can help your report
## Rubric
| Criteria | Exemplary | Adequate | Needs Improvement |
| -------- | ---------------------------------------------------------------------------------------------------------- | --------------------------- | ----------------------------- |
| | A report is presented with details drawn not only from browser tools but from 3rd party tools if available | A basic report is presented | A minimal report is presented |

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 830 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

View File

@@ -0,0 +1,153 @@
# Proyecto de extensión del navegador, parte 3: Más información sobre el rendimiento y las tareas en segundo plano
## [Pre-lecture prueba](.github/pre-lecture-quiz.md)
### Introducción:
En las dos últimas lecciones de este módulo, aprendió cómo crear un formulario y un área de visualización para los datos obtenidos de una API. Es una forma muy estándar de crear presencias web en la web. Incluso aprendió a manejar la obtención de datos de forma asincrónica. La extensión de su navegador está casi completa.
Queda por administrar algunas tareas en segundo plano, incluida la actualización del color del icono de la extensión, por lo que este es un buen momento para hablar sobre cómo el navegador administra este tipo de tareas. Pensemos en estas tareas del navegador en el contexto del rendimiento de sus activos web a medida que los crea.
## Conceptos básicos sobre el rendimiento web
> "El rendimiento del sitio web se trata de dos cosas: qué tan rápido se carga la página y qué tan rápido se ejecuta el código". - [Zack Grossbart](https://www.smashingmagazine.com/2012/06/javascript-profiling-chrome-developer-tools/)
El tema de cómo hacer que sus sitios web sean increíblemente rápidos en todo tipo de dispositivos, para todo tipo de usuarios, en todo tipo de situaciones, es sorprendentemente vasto. Estos son algunos puntos que debe tener en cuenta al crear un proyecto web estándar o una extensión de navegador.
Lo primero que debe hacer para asegurarse de que su sitio funcione de manera eficiente es recopilar datos sobre su rendimiento. El lugar para hacer esto es en las herramientas de desarrollo de su navegador web. En Edge, puede seleccionar los tres puntos en la parte superior derecha del navegador, luego navegar a Más herramientas> Herramientas de desarrollo y abrir la pestaña Rendimiento.
La pestaña Rendimiento contiene una herramienta de creación de perfiles. Abra un sitio web (pruebe, por ejemplo, https://www.microsoft.com) y haga clic en el botón 'Grabar', luego actualice el sitio. Detenga la grabación en cualquier momento y podrá ver las rutinas que se generan para 'escribir', 'renderizar' y 'pintar' el sitio:
![Edge profiler](./images/profiler.png)
✅ Visite la [Documentación de Microsoft](https://docs.microsoft.com/en-us/microsoft-edge/devtools-guide/performance) en el panel Rendimiento en Edge
> Consejo: para obtener una lectura real de la hora de inicio de su sitio web, borre la memoria caché de su navegador
Seleccione elementos de la línea de tiempo del perfil para ampliar los eventos que suceden mientras se carga su página.
Obtenga una instantánea del rendimiento de su página seleccionando una parte de la línea de tiempo del perfil y mirando el panel de resumen:
![Instantánea de Edge Profiler](./images/snapshot.png)
Compruebe el panel Registro de eventos para ver si algún evento tardó más de 15 ms:
![Registro de eventos de Edge](./images/log.png)
✅ ¡Conoce a tu perfilador! Abra las herramientas de desarrollo en este sitio y vea si hay cuellos de botella. ¿Cuál es el activo de carga más lenta? ¿El más rápido?
## Comprobaciones de perfiles
En general, hay algunas "áreas problemáticas" que todo desarrollador web debe tener en cuenta al crear un sitio, para evitar sorpresas desagradables cuando llegue el momento de implementarlo en producción.
**Tamaños de activos**: la Web se ha vuelto 'más pesada' y, por lo tanto, más lenta en los últimos años. Parte de este peso tiene que ver con el uso de imágenes.
✅ Busque en el [Archivo de Internet](https://httparchive.org/reports/page-weight) una vista histórica del peso de la página y más.
Una buena práctica es asegurarse de que sus imágenes estén optimizadas, entregadas con el tamaño y la resolución adecuados para sus usuarios.
**Recorridos de DOM**: el navegador tiene que construir su Modelo de Objetos de Documento basado en el código que usted escribe, por lo que es de interés para un buen rendimiento de la página mantener sus etiquetas al mínimo, solo usando y estilizando lo que la página necesita. Hasta este punto, se podría optimizar el exceso de CSS asociado con una página; los estilos que deben usarse solo en una página no necesitan incluirse en la hoja de estilo principal, por ejemplo.
**JavaScript**: Todo desarrollador de JavaScript debe estar atento a los scripts de 'bloqueo de renderizado' que deben cargarse antes de que el resto del DOM pueda atravesarse y pintarse en el navegador. Considere usar "diferir" con sus scripts en línea (como se hace en el módulo Terrarium).
✅ Pruebe algunos sitios en un [sitio web de prueba de velocidad del sitio](https://www.webpagetest.org/) para obtener más información sobre las comprobaciones comunes que se realizan para determinar el rendimiento del sitio.
Ahora que tiene una idea de cómo el navegador representa los recursos que le envía, veamos las últimas cosas que debe hacer para completar su extensión:
### Crea una función para calcular el color
Trabajando en `/ src / index.js`, agregue una función llamada` calculateColor () `después de la serie de variables` const` que estableció para obtener acceso al DOM:
```JavaScript
function calculateColor(value) {
let co2Scale = [0, 150, 600, 750, 800];
let colors = ['#2AA364', '#F5EB4D', '#9E4229', '#381D02', '#381D02'];
let closestNum = co2Scale.sort((a, b) => {
return Math.abs(a - value) - Math.abs(b - value);
})[0];
console.log(value + ' is closest to ' + closestNum);
let num = (element) => element > closestNum;
let scaleIndex = co2Scale.findIndex(num);
let closestColor = colors[scaleIndex];
console.log(scaleIndex, closestColor);
chrome.runtime.sendMessage({ action: 'updateIcon', value: { color: closestColor } });
}
```
¿Que está pasando aqui? Pasa un valor (la intensidad de carbono) de la llamada API que completó en la última lección, y luego calcula qué tan cerca está su valor del índice presentado en la matriz de colores. Luego, envía el valor de color más cercano al tiempo de ejecución de Chrome.
Chrome.runtime tiene [una API](https://developer.chrome.com/extensions/runtime) que maneja todo tipo de tareas en segundo plano, y tu extensión aprovecha eso:
> "Utilice la API chrome.runtime para recuperar la página de fondo, devolver detalles sobre el manifiesto y escuchar y responder a eventos en el ciclo de vida de la aplicación o extensión. También puede utilizar esta API para convertir la ruta relativa de las URL a URL calificadas".
✅ Si está desarrollando esta extensión de navegador para Edge, puede que le sorprenda que esté utilizando una API de Chrome. Las versiones más recientes del navegador Edge se ejecutan en el motor del navegador Chromium, por lo que puede aprovechar estas herramientas.
> Tenga en cuenta que si desea crear un perfil de una extensión de navegador, inicie las herramientas de desarrollo desde la propia extensión, ya que es su propia instancia de navegador independiente.
### Establecer un color de icono predeterminado
Ahora, en la función `init ()`, configure el ícono en verde genérico para comenzar nuevamente llamando a la acción `updateIcon` de Chrome:
```JavaScript
chrome.runtime.sendMessage({
action: 'updateIcon',
value: {
color: 'green',
},
});
```
### Llame a la función, ejecute la llamada
A continuación, llame a la función que acaba de crear agregándola a la promesa devuelta por la API C02Signal:
```JavaScript
//let CO2...
calculateColor(CO2);
```
Y finalmente, en `/dist/background.js`, agregue el oyente para estas llamadas de acción en segundo plano:
```JavaScript
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
if (msg.action === 'updateIcon') {
chrome.browserAction.setIcon({ imageData: drawIcon(msg.value) });
}
});
//tomado de la extensión Energy Lollipop, ¡buena característica!
function drawIcon(value) {
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
context.beginPath();
context.fillStyle = value.color;
context.arc(100, 100, 50, 0, 2 * Math.PI);
context.fill();
return context.getImageData(50, 50, 100, 100);
}
```
En este código, está agregando un oyente para cualquier mensaje que llegue al administrador de tareas de backend. Si se llama 'updateIcon', entonces se ejecuta el siguiente código para dibujar un icono del color adecuado usando la API de Canvas.
✅ Aprenderá más sobre la API Canvas en las [lecciones del juego espacial](../../space-game/drawing-to-canvas/README.md).
Ahora, reconstruya su extensión (`npm run build`), actualice y ejecute su extensión, y observe el cambio de color. ¿Es un buen momento para hacer un mandado o lavar los platos? ¡Ahora lo sabes!
Felicitaciones, ha creado una extensión de navegador útil y ha aprendido más sobre cómo funciona el navegador y cómo perfilar su rendimiento.
🚀 Desafío: Investigue algunos sitios web de código abierto que han existido hace mucho tiempo y, según su historial de GitHub, vea si puede determinar cómo se optimizaron a lo largo de los años para el rendimiento, si es que lo hicieron. ¿Cuál es el punto de dolor más común?
## [Post-lecture prueba] (.github/post-lecture-quiz.md)
## Revisión y autoestudio
Considere suscribirse a un [boletín informativo de rendimiento](https://perf.email/)
Investigue algunas de las formas en que los navegadores miden el rendimiento web consultando las pestañas de rendimiento de sus herramientas web. ¿Encuentra diferencias importantes?
**Tarea**: [Analizar el rendimiento de un sitio](assignment.md)

View File

@@ -0,0 +1,9 @@
# Analizar el rendimiento de un sitio
Proporcione un informe detallado de un sitio web, que muestre las áreas donde el rendimiento es problemático. Analice por qué el sitio es lento y qué podría hacer para acelerarlo. No confíe solo en las herramientas del navegador, investigue un poco sobre otras herramientas que pueden ayudar a su informe
## Rúbrica
| Criterios | Ejemplar | Adecuado | Necesita mejorar |
| -------- | -------------------------------------------------- -------------------------------------------------- ------ | --------------------------- | ----------------------------- |
| | Se presenta un informe con detalles extraídos no solo de las herramientas del navegador, sino también de herramientas de terceros, si están disponibles | Se presenta un informe básico | Se presenta un informe mínimo |

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 Jen Looper
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,28 @@
# 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](https://www.co2signal.com) 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](1-about-browsers/README.md)
2. [Forms and local storage](2-forms-browsers-local-storage/README.md)
3. [Background tasks and performance](3-background-tasks-and-performance/README.md)
### Credits
![a green browser extension](extension-screenshot.png)
## 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](https://principles.green/). It was originally a [web site project](https://github.com/jlooper/green).
The structure of the browser extension was influenced by [Adebola Adeniran's COVID extension](https://github.com/onedebos/covtension).
The concept behind the 'dot' icon system was suggested by the icon structure of the [Energy Lollipop](https://energylollipop.com/) browser extension for California emissions.
These lessons were written with ♥️ by [Jen Looper](https://www.twitter.com/jenlooper)

Binary file not shown.

After

Width:  |  Height:  |  Size: 292 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 181 KiB

View File

@@ -0,0 +1,28 @@
# 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.
![extension screenshot](../extension-screenshot.png)
## Getting Started
You will need to have [npm](https://npmjs.com) installed. Download a copy of this code to a folder on your computer.
Install all the required packages:
```
npm install
```
Build the extension from webpack
```
npm run build
```
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](https://www.co2signal.com/) - enter your email in the box on this page) and the [code for your region](http://api.electricitymap.org/v3/zones) corresponding to the [Electricity Map](https://www.electricitymap.org/map) (in Boston, for example, I use 'US-NEISO').
![installing](../install-on-edge.png)
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](https://energylollipop.com/) for California emissions.

View File

@@ -0,0 +1,17 @@
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
if (msg.action === 'updateIcon') {
chrome.browserAction.setIcon({ imageData: drawIcon(msg.value) });
}
});
//borrowed from energy lollipop extension, nice feature!
function drawIcon(value) {
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
context.beginPath();
context.fillStyle = value.color;
context.arc(100, 100, 50, 0, 2 * Math.PI);
context.fill();
return context.getImageData(50, 50, 100, 100);
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

View File

@@ -0,0 +1,44 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>My Carbon Trigger</title>
<link rel="stylesheet" href="./styles.css" />
</head>
<body class="container">
<img alt="plants and people" src="images/plants-people.png" />
<div>
<h1>Welcome to Your Personal Carbon Trigger!</h1>
</div>
<form class="form-data" autocomplete="on">
<div>
<h2>New? Add your Information</h2>
</div>
<div>
<label>Region Name</label>
<input type="text" required class="region-name" />
</div>
<div>
<label>Your API Key from tmrow</label>
<input type="text" required class="api-key" />
</div>
<button class="search-btn">Submit</button>
</form>
<div class="result">
<div class="loading">loading...</div>
<div class="errors"></div>
<div class="data"></div>
<div class="result-container">
<p><strong>Region: </strong><span class="my-region"></span></p>
<p><strong>Carbon Usage: </strong><span class="carbon-usage"></span></p>
<p><strong>Fossil Fuel Percentage: </strong><span class="fossil-fuel"></span></p>
</div>
<button class="clear-btn">Change region</button>
</div>
<script src="main.js"></script>
</body>
</html>

View File

View File

@@ -0,0 +1,12 @@
{
"manifest_version": 2,
"name": "My Carbon Trigger",
"version": "0.1.0",
"permissions": ["<all_urls>"],
"background": {
"scripts": ["background.js"]
},
"browser_action": {
"default_popup": "index.html"
}
}

View File

@@ -0,0 +1,143 @@
.container {
margin: 1.5em;
text-align: center;
}
.result {
margin-top: 1em;
}
.clear-btn {
text-align: center;
margin: 0 auto;
}
/*basic css*/
/* courtesy of: https://github.com/vladocar/Basic.css */
* {
box-sizing: border-box;
}
:root {
--sans: 1em/1.6 system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell,
Droid Sans, Helvetica Neue, Fira Sans, sans-serif;
--mono: SFMono-Regular, Consolas, 'Liberation Mono', Menlo, Courier, 'Courier New', monospace;
--c1: #0074d9;
--c2: #eee;
--c3: #fff;
--c4: #000;
--c5: #fff;
--m1: 8px;
--rc: 8px;
}
@media (prefers-color-scheme: dark) {
:root {
--c2: #333;
--c3: #1e1f20;
--c4: #fff;
}
}
html {
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
}
/* General settings */
body {
margin: 0;
font: var(--sans);
font-weight: 400;
font-style: normal;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
background-color: var(--c3);
color: var(--c4);
min-width: 300px;
}
img,
iframe {
border: none;
max-width: 100%;
}
a {
color: var(--c1);
text-decoration: none;
}
a:hover {
color: var(--c1);
text-decoration: underline;
}
/* Headlines */
h1,
h2 {
margin: 0.6em 0;
font-weight: normal;
}
h1 {
font-size: 1.5em;
line-height: 1.2;
}
h2 {
font-size: 1.4em;
line-height: 1.2;
}
/* Rounded Corners*/
input,
button,
img {
border-radius: var(--rc);
margin: 5px;
}
/* Forms */
input,
select,
textarea {
font-size: 1em;
color: var(--c4);
background: var(--c2);
border: 0;
padding: 0.6em;
}
label {
font-weight: bold;
text-align: left;
}
button,
input[type='submit'],
input[type='reset'],
input[type='button'] {
-webkit-appearance: none;
font-size: 1em;
display: inline-block;
color: var(--c5);
background: var(--c1);
border: 0;
margin: 4px;
padding: 0.6em;
cursor: pointer;
text-align: center;
}
button:hover,
button:focus,
input:hover,
textarea:hover,
select:hover {
opacity: 0.8;
}

View File

@@ -0,0 +1,25 @@
{
"name": "carbon-trigger-extension",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "webpack --watch",
"build": "webpack"
},
"keywords": [
"chrome extension",
"edge extension",
"carbon usage tracker"
],
"author": "Jen Looper",
"license": "MIT",
"devDependencies": {
"webpack": "^4.44.1",
"webpack-cli": "^3.3.12"
},
"dependencies": {
"axios": "^0.19.2"
}
}

View File

@@ -0,0 +1,127 @@
import axios from './node_modules/axios';
// form fields
const form = document.querySelector('.form-data');
const region = document.querySelector('.region-name');
const apiKey = document.querySelector('.api-key');
// results
const errors = document.querySelector('.errors');
const loading = document.querySelector('.loading');
const results = document.querySelector('.result-container');
const usage = document.querySelector('.carbon-usage');
const fossilfuel = document.querySelector('.fossil-fuel');
const myregion = document.querySelector('.my-region');
const clearBtn = document.querySelector('.clear-btn');
calculateColor = async (value) => {
let co2Scale = [0, 150, 600, 750, 800];
let colors = ['#2AA364', '#F5EB4D', '#9E4229', '#381D02', '#381D02'];
let closestNum = co2Scale.sort((a, b) => {
return Math.abs(a - value) - Math.abs(b - value);
})[0];
//console.log(value + ' is closest to ' + closestNum);
let num = (element) => element > closestNum;
let scaleIndex = co2Scale.findIndex(num);
let closestColor = colors[scaleIndex];
//console.log(scaleIndex, closestColor);
chrome.runtime.sendMessage({ action: 'updateIcon', value: { color: closestColor } });
};
const displayCarbonUsage = async (apiKey, region) => {
try {
await axios
.get('https://api.co2signal.com/v1/latest', {
params: {
countryCode: region,
},
headers: {
//please get your own token from CO2Signal https://www.co2signal.com/
'auth-token': apiKey,
},
})
.then((response) => {
let CO2 = Math.floor(response.data.data.carbonIntensity);
calculateColor(CO2);
loading.style.display = 'none';
form.style.display = 'none';
myregion.textContent = region;
usage.textContent =
Math.round(response.data.data.carbonIntensity) + ' grams (grams C02 emitted per kilowatt hour)';
fossilfuel.textContent =
response.data.data.fossilFuelPercentage.toFixed(2) +
'% (percentage of fossil fuels used to generate electricity)';
results.style.display = 'block';
});
} catch (error) {
console.log(error);
loading.style.display = 'none';
results.style.display = 'none';
errors.textContent = 'Sorry, we have no data for the region you have requested.';
}
};
// set up api key and region
const setUpUser = async (apiKey, regionName) => {
localStorage.setItem('apiKey', apiKey);
localStorage.setItem('regionName', regionName);
loading.style.display = 'block';
errors.textContent = '';
clearBtn.style.display = 'block';
//make initial call
displayCarbonUsage(apiKey, regionName);
};
// handle form submission
const handleSubmit = async (e) => {
e.preventDefault();
setUpUser(apiKey.value, region.value);
};
//initial checks
const init = async () => {
//if anything is in localStorage, pick it up
const storedApiKey = localStorage.getItem('apiKey');
const storedRegion = localStorage.getItem('regionName');
//set icon to be generic green
chrome.runtime.sendMessage({
action: 'updateIcon',
value: {
color: 'green',
},
});
if (storedApiKey === null || storedRegion === null) {
//if we don't have the keys, show the form
form.style.display = 'block';
results.style.display = 'none';
loading.style.display = 'none';
clearBtn.style.display = 'none';
errors.textContent = '';
} else {
//if we have saved keys/regions in localStorage, show results when they load
results.style.display = 'none';
form.style.display = 'none';
displayCarbonUsage(storedApiKey, storedRegion);
clearBtn.style.display = 'block';
}
};
const reset = async (e) => {
e.preventDefault();
//clear local storage for region only
localStorage.removeItem('regionName');
init();
};
form.addEventListener('submit', (e) => handleSubmit(e));
clearBtn.addEventListener('click', (e) => reset(e));
//start app
init();

View File

@@ -0,0 +1,28 @@
# Extensión del navegador Carbon Trigger: Código completo
Usando la API de señal C02 de tmrow para rastrear el uso de electricidad, cree una extensión de navegador para que pueda tener un recordatorio directamente en su navegador sobre el consumo de electricidad de su región. El uso de esta extensión ad hoc le ayudará a tomar decisiones sobre sus actividades basándose en esta información.
![extension screenshot](../start/extension-screenshot.png)
## Empezando
Deberá tener [npm](https://npmjs.com) instalado. Descargue una copia de este código en una carpeta de su computadora.
Instale todos los paquetes necesarios:
```
npm install
```
Construye la extensión desde webpack:
```
npm run build
```
Para instalar en Edge, use el menú de 'tres puntos' en la esquina superior derecha del navegador para encontrar el panel Extensiones. Desde allí, seleccione 'Cargar desempaquetado' para cargar una nueva extensión. Abra la carpeta 'dist' cuando se le solicite y se cargará la extensión. Para usarlo, necesitará una clave API para la API de CO2 Signal ([obtenga una aquí por correo electrónico](https://www.co2signal.com/) - ingrese su correo electrónico en el cuadro de esta página) y el [código para su región](http://api.electricitymap.org/v3/zones) correspondiente al [Mapa de electricidad](https://www.electricitymap.org/map) (en Boston, por ejemplo, utilizo 'US- NEISO').
![installing](../start/install-on-edge.png)
Una vez que se ingresa la clave API y la región en la interfaz de extensión, el punto de color en la barra de extensión del navegador debe cambiar para reflejar el uso de energía de su región y darle un indicador sobre las actividades de alto consumo de energía que serían apropiadas para usted. El concepto detrás de este sistema de "puntos" me lo dio la [extensión Energy Lollipop](https://energylollipop.com/) para las emisiones de California.

View File

@@ -0,0 +1,28 @@
# 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.
![extension screenshot](../extension-screenshot.png)
## Getting Started
You will need to have [npm](https://npmjs.com) installed. Download a copy of this code to a folder on your computer.
Install all the required packages:
```
npm install
```
Build the extension from webpack
```
npm run build
```
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](https://www.co2signal.com/) - enter your email in the box on this page) and the [code for your region](http://api.electricitymap.org/v3/zones) corresponding to the [Electricity Map](https://www.electricitymap.org/map) (in Boston, for example, I use 'US-NEISO').
![installing](../install-on-edge.png)
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](https://energylollipop.com/) for California emissions.

View File

@@ -0,0 +1,4 @@
//add listener here
//borrowed from energy lollipop extension
//draw the icon here

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

View File

@@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>My Carbon Trigger</title>
<link rel="stylesheet" href="./styles.css" />
</head>
<body class="container">
<img alt="plants and people" src="images/plants-people.png" />
<div>
<h1>Welcome to Your Personal Carbon Trigger!</h1>
</div>
<!--form area-->
<!--result area-->
<script src="main.js"></script>
</body>
</html>

View File

View File

@@ -0,0 +1,12 @@
{
"manifest_version": 2,
"name": "My Carbon Trigger",
"version": "0.1.0",
"permissions": ["<all_urls>"],
"background": {
"scripts": ["background.js"]
},
"browser_action": {
"default_popup": "index.html"
}
}

View File

@@ -0,0 +1,143 @@
.container {
margin: 1.5em;
text-align: center;
}
.result {
margin-top: 1em;
}
.clear-btn {
text-align: center;
margin: 0 auto;
}
/*basic css*/
/* courtesy of: https://github.com/vladocar/Basic.css */
* {
box-sizing: border-box;
}
:root {
--sans: 1em/1.6 system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell,
Droid Sans, Helvetica Neue, Fira Sans, sans-serif;
--mono: SFMono-Regular, Consolas, 'Liberation Mono', Menlo, Courier, 'Courier New', monospace;
--c1: #0074d9;
--c2: #eee;
--c3: #fff;
--c4: #000;
--c5: #fff;
--m1: 8px;
--rc: 8px;
}
@media (prefers-color-scheme: dark) {
:root {
--c2: #333;
--c3: #1e1f20;
--c4: #fff;
}
}
html {
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
}
/* General settings */
body {
margin: 0;
font: var(--sans);
font-weight: 400;
font-style: normal;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
background-color: var(--c3);
color: var(--c4);
min-width: 300px;
}
img,
iframe {
border: none;
max-width: 100%;
}
a {
color: var(--c1);
text-decoration: none;
}
a:hover {
color: var(--c1);
text-decoration: underline;
}
/* Headlines */
h1,
h2 {
margin: 0.6em 0;
font-weight: normal;
}
h1 {
font-size: 1.5em;
line-height: 1.2;
}
h2 {
font-size: 1.4em;
line-height: 1.2;
}
/* Rounded Corners*/
input,
button,
img {
border-radius: var(--rc);
margin: 5px;
}
/* Forms */
input,
select,
textarea {
font-size: 1em;
color: var(--c4);
background: var(--c2);
border: 0;
padding: 0.6em;
}
label {
font-weight: bold;
text-align: left;
}
button,
input[type='submit'],
input[type='reset'],
input[type='button'] {
-webkit-appearance: none;
font-size: 1em;
display: inline-block;
color: var(--c5);
background: var(--c1);
border: 0;
margin: 4px;
padding: 0.6em;
cursor: pointer;
text-align: center;
}
button:hover,
button:focus,
input:hover,
textarea:hover,
select:hover {
opacity: 0.8;
}

View File

@@ -0,0 +1,25 @@
{
"name": "carbon-trigger-extension",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "webpack --watch",
"build": "webpack"
},
"keywords": [
"chrome extension",
"edge extension",
"carbon usage tracker"
],
"author": "Jen Looper",
"license": "MIT",
"devDependencies": {
"webpack": "^4.44.1",
"webpack-cli": "^3.3.12"
},
"dependencies": {
"axios": "^0.19.2"
}
}

View File

@@ -0,0 +1,17 @@
//1
// form fields
// results divs
//6
//call the API
//5
//set up user's api key and region
//4
// handle form submission
//3 initial checks
//2
// set listeners and start app

View File

@@ -0,0 +1,28 @@
# Extensión del navegador Carbon Trigger: Código de inicio
Usando la API de señal C02 de tmrow para rastrear el uso de electricidad, cree una extensión de navegador para que pueda tener un recordatorio directamente en su navegador sobre el consumo de electricidad de su región. El uso de esta extensión ad hoc le ayudará a tomar decisiones sobre sus actividades basándose en esta información.
![extension screenshot](extension-screenshot.png)
## Empezando
Deberá tener [npm](https://npmjs.com) instalado. Descargue una copia de este código en una carpeta de su computadora.
Instale todos los paquetes necesarios:
```
npm install
```
Construye la extensión desde webpack:
```
npm run build
```
Para instalar en Edge, use el menú de 'tres puntos' en la esquina superior derecha del navegador para encontrar el panel Extensiones. Desde allí, seleccione 'Cargar sin empaquetar' para cargar una nueva extensión. Abra la carpeta 'dist' cuando se le solicite y se cargará la extensión. Para usarlo, necesitará una clave API para la API de CO2 Signal ([obtenga una aquí por correo electrónico](https://www.co2signal.com/) - ingrese su correo electrónico en el cuadro de esta página) y el [código para su región] (http://api.electricitymap.org/v3/zones) correspondiente al [Mapa de electricidad](https://www.electricitymap.org/map) (en Boston, por ejemplo, utilizo 'US- NEISO').
![instalación](install-on-edge.png)
Una vez que se ingresa la clave API y la región en la interfaz de extensión, el punto de color en la barra de extensión del navegador debe cambiar para reflejar el uso de energía de su región y darle un indicador sobre las actividades de alto consumo de energía que serían apropiadas para usted. El concepto detrás de este sistema de "puntos" me lo dio la [extensión Energy Lollipop](https://energylollipop.com/) para las emisiones de California.

View File

@@ -0,0 +1,28 @@
# Construyendo una extensión de navegador
Crear extensiones de navegador es una forma divertida e interesante de pensar en el rendimiento de sus aplicaciones mientras crea un tipo diferente de activo web. Este módulo incluye lecciones sobre cómo funcionan los navegadores y cómo implementar una extensión de navegador, cómo crear un formulario, llamar a una API y usar el almacenamiento local, y cómo medir el rendimiento de su sitio web y mejorarlo.
Construirá una extensión de navegador que funcione en Edge, Chrome y Firefox. Esta extensión, que es como un mini sitio web que está diseñado para una tarea muy específica, verifica la [API de señal C02](https://www.co2signal.com) para el uso de electricidad y la intensidad de carbono de una región determinada, y devuelve un lectura sobre la huella de carbono de la región.
Esta extensión puede ser llamada ad hoc por un usuario una vez que se ingresa una clave API y un código de región en un formulario para determinar el uso de electricidad local y, por lo tanto, ofrecer datos que pueden influir en las decisiones de electricidad de un usuario. Por ejemplo, puede ser preferible retrasar el funcionamiento de una secadora de ropa (una actividad intensa en carbono) durante un período de alto consumo de electricidad en su región.
### Temas
1. [Sobre el navegador](about-browsers/README.md)
2. [Formularios y almacenamiento local](forms-browsers-local-storage/README.md)
3. [Desempeño y tareas en segundo plano](background-tasks-and-performance/README.md)
### Créditos
![a green browser extension](extension-screenshot.png)
## Créditos
La idea de este disparador de carbono web fue ofrecida por Asim Hussain, líder en Microsoft del equipo de defensa de la nube verde y autor de los [Principios verdes](https://principles.green/). Originalmente era un [proyecto de sitio web](https://github.com/jlooper/green).
La estructura de la extensión del navegador fue influenciada por la [extensión COVID de Adebola Adeniran](https://github.com/onedebos/covtension).
El concepto detrás del sistema de iconos 'puntos' fue sugerido por la estructura de iconos de la extensión del navegador [Energy Lollipop](https://energylollipop.com/) para las emisiones de California.
Estas lecciones fueron escritas con ♥ por [Jen Looper](https://www.twitter.com/jenlooper)