As a Google Chrome shopper, you’ve maximum surely used some extensions in that browser. Have you ever ever ever wondered how they’re built or if that you just will have to assemble one?
This text guides you all through the process of making a Chrome extension, specifically one who uses React and the Kinsta API to regulate plugins on WordPress internet sites hosted with Kinsta.
What’s a Chrome extension?
A Chrome extension is a program installed throughout the Chrome browser and enhances its capacity. Extensions can range from simple icon buttons throughout the toolbar to completely integrated choices that have interaction deeply in conjunction with your browsing experience.
Learn to create a Chrome extension
Creating a Chrome extension is similar to rising a internet utility, however it requires a JSON-formatted file known as manifest.json. This file acts for the reason that backbone of the extension, dictating its settings, permissions, and functionalities you need to return with.
To begin out, create a folder that may grab all your extension data. Next, create a manifest.json file throughout the folder.
A fundamental manifest.json file for a Chrome extension comprises key homes that define the extension’s fundamental settings. Beneath is an example of a manifest.json file that incorporates the essential fields to make it artwork:
{
"manifest_version": 3,
"name": "My Chrome extension",
"type": "1.0",
"description": "Here is a description for my Chrome extension."
}
You’ll have the ability to load and check out this as an unpacked extension to Chrome. Navigate to chrome://extensions
for your browser and toggle Developer mode, then click on at the Load Unpacked button. This will every so often open a file browser, and also you’ll choose the record you created to your extension.
When you click on at the extension icon, no longer the rest will happen because of you haven’t created a client interface.
Create a client interface (popup) to your Chrome extension
Like with every web application, the patron interface (UI) of your extension uses HTML to development the content material subject material, CSS to style it, and JavaScript so to upload interactivity.
Let’s create a fundamental UI the use of all of the ones data. Get began by the use of rising an HTML file (popup.html). This file defines the development of your UI portions, paying homage to text, headings, images, and buttons. Add the following code:
Hello World
Hello World!
My first Chrome Extension
src="popup.js">
The code above creates a heading, paragraph, and button. The CSS and JavaScript data are also hooked up. Now, add some sorts throughout the popup.css file:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
background-color: aliceblue;
padding: 20px;
}
Next, throughout the popup.js file, add an event listener to the button so that when it’s clicked, an alert is displayed:
const sayHelloBtn = record.getElementById('sayHello');
sayHelloBtn.addEventListener('click on on', async () => {
let tab = look ahead to chrome.tabs.query({ full of life: true });
chrome.scripting.executeScript({
function: { tabId: tab[0].identification },
function: () => alert('Hello from the extension!'),
});
});
This JavaScript code retrieves the existing full of life tab and uses the Chrome Scripting API to execute a script that presentations an alert with a greeting message when the Say Hello button is clicked. This introduces fundamental interactivity on your Chrome extension.
With the ones steps, you will have organize a simple popup UI to your Chrome extension that incorporates fundamental text, styling, and capacity.
Finally, you need to allow the popup file throughout the manifest.json file by the use of together with some permissions:
{
. . . ,
"movement": {
"default_popup": "popup.html"
},
"permissions": [
"scripting",
"tabs"
],
"host_permissions": [
"http://*/*",
"https://*/*"
]
}
Inside the configuration above, the default_popup
key specifies that popup.html will be the default UI when the patron interacts with the extension. The permissions
array comprises scripting
and tabs
, which may well be crucial for the extension to interact with the tabs and use the browser’s scripting choices.
The host_permissions
array specifies which web websites your extension can have interaction with. The patterns http://*/*
and https://*/*
indicate that your extension can have interaction with all web websites accessed over HTTP and HTTPS protocols.
With the ones settings for your manifest.json file, your Chrome extension is accurately configured to turn a popup and execute scripts.
Reload your Chrome extension
With the ones changes effected for your local folder, you need to switch the unpacked folder loaded to Chrome. To take a look at this, open the Chrome extensions internet web page, find your extension, and click on at the reload icon.
You’ll have the ability to then click on at the extension icon, and a popup will appear. When you click on at the Say Hello button, an alert will appear.
You now have a fundamental knowledge of get started development a Chrome extension. There’s further that can be achieved. You’ll have the ability to manipulate your web page’s UI, make API requests, retrieve data from URLs to perform specific operations, and further.
Learn to create a Chrome extension with React
As we mentioned earlier, creating a Chrome extension is similar to development a web application. You’ll have the ability to use in style web frameworks like React.
For React, the manifest.json file is created throughout the public folder. This folder is used for static assets you don’t wish to be processed by the use of Webpack (or equivalent bundlers that React would in all probability use beneath the hood in tools like Create React App).
When you assemble your React application, the assemble process copies all contents of the public folder into the dist folder. That is create a Chrome extension with React:
- Create a brand spanking new React application. You’ll have the ability to use the local development environment Vite by the use of operating the following command for your terminal:
npm create vite@latest
Next, give your problem a name and choose React for the reason that framework. Once this is achieved, navigate into the problem folder and arrange the dependencies:
cd
npm arrange
- For your React problem’s public folder, create a manifest.json file. Add the following configurations:
{
"manifest_version": 3,
"name": "React Chrome extension",
"description": "Chrome extension built with React",
"type": "0.1.0",
"movement": {
"default_popup": "index.html"
},
"permissions": [
"tabs"
],
"host_permissions": [
"http://*/*",
"https://*/*"
]
}
The configuration for a Chrome extension comprises an movement
object that devices index.html for the reason that default popup when the extension icon is clicked. That’s the static HTML file generated when you assemble your React application.
- Build up the React application. Feel free to make API requests, style them as you need, use React Hooks, and further.
- If you end up achieved development the UI of the extension, run the assemble command in React (
npm run assemble
). All your assets, in conjunction with your manifest.json file, React-generated index.html, and others, are moved into the dist or assemble folder. - Finally, load your extension into Chrome. Navigate to
chrome://extensions/
and reload your extension.
Creating a Chrome extension to regulate your web page’s plugins with Kinsta API
That’s what the Chrome extension you’ll assemble will appear to be:
When clicked, the extension presentations a list of internet sites with outdated plugins for your MyKinsta account. You’ll have the ability to see a list of the plugins and click on at the View in MyKinsta button to navigate to the web page’s Issues & Plugins internet web page, where you’ll change each and every plugin.
Let’s uncover create the Chrome extension.
Understanding the Kinsta API
The Kinsta API is an impressive instrument that allows you to have interaction programmatically with Kinsta services and products and merchandise like hosted WordPress internet sites. It would help automate various tasks related to WordPress regulate, in conjunction with website introduction, retrieving website knowledge, getting a website’s standing, surfing and restoring backups, and further.
To use Kinsta’s API, you will have an account with at least one WordPress web page, utility, or database in MyKinsta. You will have to moreover generate an API key to authenticate and get admission to your account.
To generate an API key:
- Go on your MyKinsta dashboard.
- Navigate to the API Keys internet web page (Your name > Company settings > API Keys).
- Click on on Create API Key.
- Make a choice an expiration or set a custom designed get began date and selection of hours for the essential factor to expire.
- Give the essential factor a unique name.
- Click on on Generate.
After rising an API key, reproduction it and store it somewhere safe (the use of a password supervisor is advisable). You’ll have the ability to generate a couple of API keys, which will be listed on the API Keys internet web page. If you wish to revoke an API key, click on at the Revoke button.
Arrange your web page’s plugins with Kinsta API and React
Let’s get began by the use of rising a client interface in React, which is in a position to then be revamped proper right into a Chrome extension. This data assumes fundamental familiarity with React and API interaction.
Setting up the environment
At the start, throughout the App.jsx file, define a continuing for the Kinsta API URL to avoid redundancy for your code:
const KinstaAPIUrl = 'https://api.kinsta.com/v2';
For protection, store subtle data paying homage to your API key and Kinsta company ID in a .env.local file to stick them protected and out of your provide code:
VITE_KINSTA_COMPANY_ID=YOUR_COMPANY_ID
VITE_KINSTA_API_KEY=YOUR_API_KEY
Fetch data with Kinsta API
Inside the App.jsx file, you need to make a variety of requests to the Kinsta API to retrieve information about internet sites and their plugins.
- Retrieve company internet sites: Get started by the use of fetching a list of internet sites similar in conjunction with your Kinsta company account. Use the company ID in a GET request, which returns an array of web page details.
const getListOfCompanySites = async () => { const query = new URLSearchParams({ company: import.meta.env.VITE_KINSTA_COMPANY_ID, }).toString(); const resp = look ahead to fetch(`${KinstaAPIUrl}/internet sites?${query}`, { way: 'GET', headers: { Authorization: `Bearer ${import.meta.env.VITE_KINSTA_API_KEY}`, }, }); const data = look ahead to resp.json(); const companySites = data.company.internet sites; return companySites; }
- Fetch environment data for each and every web page: For each and every web page, retrieve the environments, which include the environment ID essential for extra requests. This involves mapping over each and every web page and making an API identify to the
/internet sites/${siteId}/environments
endpoint.const companySites = look ahead to getListOfCompanySites(); // Get all environments for each and every web page const sitesEnvironmentData = companySites.map(async (web page) => { const siteId = web page.identification; const resp = look ahead to fetch(`${KinstaAPIUrl}/internet sites/${siteId}/environments`, { way: 'GET', headers: { Authorization: `Bearer ${import.meta.env.VITE_KINSTA_API_KEY}`, }, }); const data = look ahead to resp.json(); const environments = data.web page.environments; return { identification: siteId, name: web page.display_name, environments: environments, }; });
- Retrieve plugins for each and every web page environment: Finally, use the environment ID to fetch plugins for each and every web page. This step involves a mapping function and an API identify to the
/internet sites/environments/${environmentId}/plugins
endpoint for each and every environment.// Stay up for the entire promises to resolve const sitesData = look ahead to Promise.all(sitesEnvironmentData); // Get all plugins for each and every environment const sitesWithPlugin = sitesData.map(async (web page) => { const environmentId = web page.environments[0].identification; const resp = look ahead to fetch( `${KinstaAPIUrl}/internet sites/environments/${environmentId}/plugins`, { way: 'GET', headers: { Authorization: `Bearer ${import.meta.env.VITE_KINSTA_API_KEY}`, }, } ); const data = look ahead to resp.json(); const plugins = data.environment.container_info; return { env_id: environmentId, name: web page.name, site_id: web page.identification, plugins: plugins, }; });
You’ll have the ability to now put all of the ones requests together proper right into a function that is used to return the overall array of internet sites with fundamental details about each and every web page and its plugins:
const getSitesWithPluginData = async () => { const getListOfCompanySites = async () => { const query = new URLSearchParams({ company: import.meta.env.VITE_KINSTA_COMPANY_ID, }).toString(); const resp = look ahead to fetch(`${KinstaAPIUrl}/internet sites?${query}`, { way: 'GET', headers: { Authorization: `Bearer ${import.meta.env.VITE_KINSTA_API_KEY}`, }, }); const data = look ahead to resp.json(); const companySites = data.company.internet sites; return companySites; } const companySites = look ahead to getListOfCompanySites(); // Get all environments for each and every web page const sitesEnvironmentData = companySites.map(async (web page) => { const siteId = web page.identification; const resp = look ahead to fetch(`${KinstaAPIUrl}/internet sites/${siteId}/environments`, { way: 'GET', headers: { Authorization: `Bearer ${import.meta.env.VITE_KINSTA_API_KEY}`, }, }); const data = look ahead to resp.json(); const environments = data.web page.environments; return { identification: siteId, name: web page.display_name, environments: environments, }; }); // Stay up for the entire promises to resolve const sitesData = look ahead to Promise.all(sitesEnvironmentData); // Get all plugins for each and every environment const sitesWithPlugin = sitesData.map(async (web page) => { const environmentId = web page.environments[0].identification; const resp = look ahead to fetch( `${KinstaAPIUrl}/internet sites/environments/${environmentId}/plugins`, { way: 'GET', headers: { Authorization: `Bearer ${import.meta.env.VITE_KINSTA_API_KEY}`, }, } ); const data = look ahead to resp.json(); const plugins = data.environment.container_info; return { env_id: environmentId, name: web page.name, site_id: web page.identification, plugins: plugins, }; }); // Stay up for the entire promises to resolve const sitesWithPluginData = look ahead to Promise.all(sitesWithPlugin); return sitesWithPluginData; }
Appearing web page data
Create a state with the useState
hook to store internet sites with outdated plugin(s). The useEffect
hook may additionally identify the getSitesWithPluginData()
way and extract the web page details when the part is mounted.
Inside the useEffect
hook, create a function that may loop by the use of each and every web page to filter out internet sites with outdated plugins and then store them throughout the state:
const [sitesWithOutdatedPlugin, setSitesWithOutdatedPlugin] = useState([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const checkSitesWithPluginUpdate = async () => {
const sitesWithPluginData = look ahead to getSitesWithPluginData();
const sitesWithOutdatedPlugin = sitesWithPluginData.map((web page) => {
const plugins = web page.plugins.wp_plugins.data;
const outdatedPlugins = plugins.clear out((plugin) => plugin.change === "available");
if (outdatedPlugins.length > 0) {
const kinstaDashboardPluginPageURL = `https://my.kinsta.com/internet sites/plugins/${web page.site_id}/${web page.env_id}?idCompany=${import.meta.env.VITE_KINSTA_COMPANY_ID}`;
return {
name: web page.name,
plugins: outdatedPlugins,
url: kinstaDashboardPluginPageURL,
};
}
});
setSitesWithOutdatedPlugin(sitesWithOutdatedPlugin);
checkSitesWithPluginUpdate();
setIsLoading(false);
}, []);
Inside the code above, you remember that the loading state may be created and set to true
by the use of default. This will be used to control how data is displayed. When the entire data is loaded, we set it to false
.
Beneath is a markup to render the web page data and plugins within your UI.
import { useEffect, useState } from "react"
import KinstaLogo from './assets/kinsta-logo.png'
import PluginPage from './parts/PluginsPage'
function App() {
// load the guidelines from the API
return (
className="title-section">
className="info-box">
Get rapid information about your web page plugins that need change.
{isLoading ? (
Loading...
) : (
The following internet sites have plugins that wish to be up to the moment.
{sitesWithOutdatedPlugin.map((web page, index) => {
return (
);
})}
)}
)
}
export default App
The code includes a header with a symbol and an informational paragraph. The content material subject material of the UI is conditionally rendered in line with the isLoading
state. If data continues to be loading, it presentations a loading message. Once data is loaded, it pieces the guidelines regarding the internet sites and any plugins requiring updates.
You’ll moreover perceive a component: PluginPage
(PluginPage.jsx). This part is designed to turn particular person internet sites and their plugin details. It includes a capacity to toggle the visibility of the plugin details.
import { useState } from "react"
import { FaRegEye } from "react-icons/fa";
import { FaRegEyeSlash } from "react-icons/fa";
const PluginUse = (web page) => {
const [viewPlugin, setViewPlugin] = useState(false);
return (
{web page.name}
{viewPlugin && (
{web page.plugins.map((plugin, index) => {
return (
{plugin.name}
Provide Style: {plugin.type}
Latest Style: {plugin.update_version}
);
})}
)}
)
}
export default PluginUse
Configure the manifest file
To become your shopper interface and capacity proper right into a Chrome extension, you need to configure the manifest.json file.
Create a manifest.json file throughout the public folder and paste the code underneath:
{
"manifest_version": 3,
"name": "Kinsta Plugins Manager - As a result of Kinsta API",
"description": "This extension implies that you'll be able to arrange your WordPress web page's plugin from Kinsta's MyKinsta dashboard by means of Kinsta API.",
"type": "0.1.0",
"icons": {
"48": "kinsta-icon.png"
},
"movement": {
"default_popup": "index.html"
},
"permissions": [
"tabs"
],
"host_permissions": [
"https://my.kinsta.com/*"
]
}
You will have to surely add the icon file on your public folder.
At this stage, you’ll now run the assemble command (npm run assemble
) so all your assets, in conjunction with your manifest.json file, React-generated index.html, and other data, are moved into the dist or assemble folder.
Next, navigate to chrome://extensions/
and load this as an unpacked extension to Chrome. Click on at the Load Unpacked button and choose the record you created to your extension.
Limit extension to specific internet sites
You remember that this extension works at any time. We’d adore it to artwork absolute best when a client is navigated to the MyKinsta dashboard.
To take a look at this, let’s control the App.jsx file. Create a state to store the full of life tab:
const [activeTab, setActiveTab] = useState(null);
Next, change the useEffect
Hook to stipulate and invoke the getCurrentTab
function:
const getCurrentTab = async () => {
const queryOptions = { full of life: true, currentWindow: true };
const
= look ahead to chrome.tabs.query(queryOptions);
setActiveTab(tab);
}
getCurrentTab();
The above code uses chrome.tabs.query
with specific query alternatives to ensure it retrieves absolute best the full of life tab throughout the provide window. As quickly because the tab is retrieved, it’s set for the reason that full of life tab within the extension’s state.
Finally, enforce a conditional rendering excellent judgment for your part’s return commentary. This promises that the plugin regulate UI turns out absolute best when the patron is on the MyKinsta dashboard:
return (
{activeTab?.url.comprises('my.kinsta.com') ? (
Get rapid information about your web page plugins that need change.
{isLoading ? (
Loading...
) : (
The following {sitesWithPluginUpdate} internet sites have plugins that wish to be up to the moment.
{sitesWithOutdatedPlugin.map((web page, index) => {
return (
);
})}
)}
) : (
This extension is absolute best available on Kinsta Dashboard.
)}
)
After making the changes, rebuild your application and reload the Chrome extension. This will every so often practice the new excellent judgment and restrictions.
Summary
In this article, you will have came upon the basics of making a Chrome extension and create one with React. You’ve moreover came upon create an extension that interacts with the Kinsta API.
As a Kinsta shopper, you’ll take pleasure in the huge conceivable and flexibility the Kinsta API brings as a result of it’s serving to you building up custom designed solutions to regulate your internet sites, programs, and databases.
What endpoint of the Kinsta API have you ever ever been the use of such a lot, and the best way have you ever ever used it? Percentage with us throughout the commentary section!
The post Learn how to construct a Chrome extension to control your website’s plugins with Kinsta API and React gave the impression first on Kinsta®.
Contents
- 1 Hello World!
- 1.1 Learn to create a Chrome extension with React
- 1.2 Creating a Chrome extension to regulate your web page’s plugins with Kinsta API
- 1.3 Arrange your web page’s plugins with Kinsta API and React
- 1.4 Summary
- 1.5 The way to Arrange the Best possible Divi Web hosting Server on Cloudways
- 1.6 Find out how to Create Drop-Down Menus in Excel
- 1.7 Wish to Write a Process Be offering Letter? I’ve Were given You Coated [+ Free Template & Exampl...
0 Comments