- How to Build a Simple Chrome Extension in Vanilla JavaScript
- Author: Sara Wegman
- The Nuggets translation Project
- Permanent link to this article: github.com/xitu/gold-m…
- Translator: Shery
- Proofreader: Park-Ma CoderMing
Today, I’m going to show you how to develop Chrome extensions using native JavaScript — that is, pure JavaScript without frameworks like React, Angular, Vue, etc.
Developing Chrome extensions was pretty easy — in my first year of programming, I released two extensions that were both developed using only HTML, CSS, and pure JavaScript. In this article, I’ll walk you through the same process in a few minutes.
I’ll show you how to develop a simple Dashboard-type Chrome extension. However, if you have your own ideas and just want to know what you need to add to your existing project to make it work in Chrome, you can jump to the section for custom manifest.json files and ICONS.
About Chrome extension
Chrome extensions are essentially just a set of files that you can customize your Google Chrome browser experience. There are several different types of Chrome extensions; Some activate when certain conditions are met, such as when you arrive at a store checkout page; Some pop up only when you click on the icon; Others appear every time a new TAB is opened. The two extensions I released this year were of the “new TAB” type; The first is Compliment Dash, a dashboard for keeping to-do lists and praising users, and the second is Liturgical. Li, a tool for pastors. If you know how to develop simple web pages, you can easily develop such extensions.
The premise
We want to keep things simple, so in this tutorial we’ll just use HTML, CSS, and some basic JavaScript, and how to customize the manifest.json file THAT I’ll add below. Chrome extensions can vary in complexity, so the complexity of building Chrome extensions depends on what kind of application you want to develop. Once you’ve learned the basics, you can use your own technology stack to develop more complex extensions.
Create your project file
In this tutorial, we will develop a simple dashboard that welcomes users by name. Let’s call it the Simple Greeting Dashboard.
First, you need to create three files: index.html, main.css, and main.js. Put them in a separate folder. Next, populate the HTML file with basic HTML code and reference the CSS and JS files:
<! -- ================================= Simple Greeting Dashboard ================================= //--> <! DOCTYPE html> <html> <head> <meta charset="utf-8" />
<title>Simple Greeting Dashboard</title>
<link rel="stylesheet" type="text/css" media="screen" href="main.css"/> </head> <body> <! This is where the business code will be added --> <script SRC ="main.js"></script>
</body>
</html>
Copy the code
Customize your manifest.json file
These files are not enough to get your project running as a Chrome extension. To do this, we need a manifest.json file, which we’ll customize with some basic extender information. You can download this file from Google’s developer site, or you can copy/paste the following code directly into a new file and save it in your folder as manifest.json:
{
"name": "Getting Started Example"."version": "1.0"."description": "Build an Extension!"."manifest_version"2} :Copy the code
Now, let’s update the sample file with more extender information. We just want to change the first three values of this code: name, version, and Description. Let’s fill in the extension name and a one-line description, since this is our first release, let’s keep the version value at 1.0. The Manifest_version number should remain unchanged.
Next, we’ll add a few lines of code to tell Chrome how to handle the extension.
{
"name": "Simple Greeting Dashboard"."version": "1.0"."description": "This Chrome extension greets the user each time they open a new tab"."manifest_version": 2
"incognito": "split"."chrome_url_overrides": {
"newtab": "index.html"
},
"permissions": [
"activeTab"]."icons": {
"128": "icon.png"}}Copy the code
The “incognito”: “split” field tells Chrome how to handle the extension when it is in incognito mode. When the browser is in incognito mode, “split” allows the extension to run in its own process; See the Chrome developer documentation for additional options.
As you might see, the “chrome_url_overrides” tells Chrome to open index.html every time it opens a new TAB. The permissions” value provides users with a pop-up prompt when they attempt to install the extension, letting them know that the extension will overwrite their new tags.
Finally, we tell Chrome what to display as our icon: a file called icon.png that measures 128 x 128 pixels.
Create an icon
Since we do not yet have an icon file, we will next create an icon for the Simple Greeting Dash. Feel free to use the icon I made below. If you want to make one yourself, you can easily do it using a free service like Photoshop or Canva. Make sure the dimensions are 128 x 128 pixels and save it as icon.png in the same folder as your HTML, CSS, JS, and JSON files.
The 128 x 128 icon I made for Simple Greeting Dash
Upload files (if you are developing your own page)
With the information above, you can create your own new TAB Chrome extension. After customizing the manifest.json file, you can design new tabs of any type you want using HTML, CSS, and JavaScript and upload them as shown below. However, if you want to see how I would make this simple dashboard, jump to create Settings Menu.
Once you’ve styled your new TAB page, your Chrome extension is complete and ready to upload to Chrome. To upload your completed extensions yourself, go to Chrome :// Extensions/in your browser and toggle developer mode in the upper right corner.
Refresh the page and click Load Unzipped extension.
Next, select the folder to store HTML, CSS, JS, and manifest.json, as well as your icon.png files, and upload these files. The extension should take effect every time a new TAB is opened!
Once you’ve finished developing the extension and testing it yourself, you can get a developer account and go to the Chrome Extension Store. This guide to publishing extensions should help.
If you’re not creating your own extension right now and just want to see what Chrome extensions can do, read on to learn how to make a very simple greeting dashboard.
Create Settings menu
For my extension, the first thing I do is create an input box that allows my users to add their names. Since I don’t want this input field to be visible all the time, I’ll put it in a div called Settings, and I’ll only make it visible when I click the Settings button.
<button id="settings-button">Settings</button>
<div class="settings" id="settings">
<form class="name-form" id="name-form" action="#">
<input class="name-input" type="text"
id="name-input" placeholder="Type your name here...">
<button type="submit" class="name-button">Add</button>
</form>
</div>
Copy the code
Now, our Settings menu looks like this:
Too beautiful!
. So I’m going to add some basic styles to them in the CSS file. I’ll add some inner margins and Outlines for the buttons and input fields, and then add some space between the Settings button and the form.
.settings {
display: flex;
flex-direction: row;
align-content: center;
}
input {
padding: 5px;
font-size: 12px;
width: 150px;
height: 20px;
}
button {
height: 30px;
width: 70px;
background: none; /* This removes the default background */
color: # 313131;
border: 1px solid # 313131;
border-radius: 50px; /* This gives our button rounded edges */
font-size: 12px;
cursor: pointer;
}
form {
padding-top: 20px;
}
Copy the code
Now our Settings menu looks a little better:
But let’s hide them if the user doesn’t click the Settings button. I’ll do this by adding the following style to the.Settings form, which will cause the name input field to disappear from one side of the screen:
transform: translateX(-100%);
transition: transform 1s;
Copy the code
Now let’s create a style class name called settings-open, and when the user clicks the Settings button, we’ll toggle adding and removing this class name in JavaScript. When settings-open is added to the Settings form, it does not apply any transformations; It’s just visible where it should be.
.settings-open.settings {
transform: none;
}
Copy the code
Let’s make class name switching work in JavaScript. I’m going to create a function called openSettings() that will add or remove the class name settings-open. To do this, I’ll first get the element with its ID “Settings” and then add the class name settings-open using classlist.toggle.
function openSettings() {
document.getElementById("settings").classList.toggle("settings-open");
}
Copy the code
Now I’m going to add an event listener that will trigger this function when I click the Settings button.
document.getElementById("settings-button").addEventListener('click', openSettings)
Copy the code
When you click the Settings button, this will make your Settings form appear or disappear.
Create personalized greetings
Next, let’s create a greeting message. We’ll create an empty H2 tag in HTML, and then fill it with innerHTML in JavaScript. I’ll give the H2 tag an ID so I can access it later and center it in a div called greeting-Container.
<div class="greeting-container">
<h2 class="greeting" id="greeting"></h2>
</div>
Copy the code
Now, in JavaScript, I’ll create a basic greeting using the user name. First, I will declare a variable save name, which is now empty and will be added later.
var userName;
Copy the code
Even if userName isn’t empty, Chrome won’t use the same name if I just put userName in a greeting in HTML if I open it in another session. To make sure Chrome remembers who I am, I’ll have to use local storage. So I’ll create a function called saveName().
function saveName() {
localStorage.setItem('receivedName', userName);
}
Copy the code
The localstorage.setitem () function takes two arguments: the first is the key I use to access the information later, and the second is the information it needs to remember; In this case, the information you need to remember is userName. Later I’ll get the saved information via localstorage.getitem, which I’ll use to update the userName variable.
var userName = localStorage.getItem('receivedName');
Copy the code
Before we link it to the event listener in the form, I want to tell Chrome what to call me if I haven’t already told it my name. I’ll do this using an if statement.
if (userName == null) {
userName = "friend";
}
Copy the code
Now, let’s finally associate the userName variable with our form. I want to do this inside the function so that it can be called every time the name is updated. We’ll call this function changeName().
function changeName() {
userName = document.getElementById("name-input").value;
saveName();
}
Copy the code
I want to call this function every time someone submits a name using the form. I’ll use an event listener to do this, and I’ll call the function changeName() and block the page’s default refresh behavior when I submit the form.
document.getElementById("name-form").addEventListener('submit'.function(e) {
e.preventDefault()
changeName();
});
Copy the code
Finally, let’s create greetings. I also put it in a function so I can call it when I refresh the page and whenever changeName() occurs. Here’s what the function says:
function getGreeting() {
document.getElementById("greeting").innerHTML = `Hello, ${userName}. Enjoy your day! `; } getGreeting()Copy the code
Now I’ll call getGreeting() in the changeName() function, and call it a day!
Finally, design your page
Now it’s time to add the finishing touches. In CSS, I’ll use Flexbox to center my title, set a larger font for the title, and add a gradient background for the body. To contrast the buttons and H2 labels with the gradient background, I’ll make them white.
.greeting-container {
display: flex;
justify-content: center;
align-content: center;
}
.greeting {
font-family: sans-serif;
font-size: 60px;
color: #fff;
}
body {
background-color: #c670ca;
background-image: linear-gradient(45deg, #c670ca 0%, #25a5c8 52%, #20e275 90%);
}
html {
height: 100%;
}
Copy the code
That’s it! Your page will look like this:
Your own Chrome extension!
It may not have a lot of features, but it’s a good base from which to create and design your own Chrome Dashboards. Let us know if you have any questions and feel free to contact me on Twitter @saralaughed.
If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.