
بروزرسانی: 26 خرداد 1404
نحوه ایجاد یک افزونه کروم با جاوا اسکریپت Vanilla
این آموزش نحوه ساخت یک برنامه افزودنی صفحه اصلی کروم حداقلی را با جاوا اسکریپت که برای کمک به کاربران در ماندگاری سازنده طراحی شده است را پوشش می دهد.
افزونه کروم برنامه ای است که تجربه مرور را برای کاربران کروم بهبود می بخشد و سفارشی می کند. در میان انواع مختلف افزونه های موجود، پسوندهای صفحه اصلی محبوب ترین هستند. این افزونه ها به کاربران اجازه می دهند صفحه شروع مرورگر خود را شخصی سازی کنند و اغلب ویژگی ها و ابزارهایی را برای بهبود بهره وری اضافه می کنند.
صفحه اصلی حاوی عناصر زیر خواهد بود:
- عنصری که آب و هوای فعلی را نشان می دهد
- عنصری که تاریخ و زمان فعلی را نشان می دهد
- یک نوار جستجو
- نقل قول های تصادفی در پایین صفحه
در پایان این آموزش، یک صفحه اصلی مینیمالیستی زیبا خواهیم داشت که به شکل زیر است:



اجزای یک برنامه افزودنی کروم
یک برنامه افزودنی کروم معمولاً از اجزای زیر تشکیل می شود:
- یک فایل مانیفست
- فایل های کاربردی که شامل فایل های HTML، فایل های جاوا اسکریپت، فایل های CSS، تصاویر، آیکون ها و سایر دارایی های لازم برای عملکرد برنامه افزودنی است.
آشکار
مانیفست الف است .json
فایلی که حاوی دستورالعمل نحوه اجرای برنامه افزودنی است. همچنین شامل مجوزهایی است که پسوند به آن نیاز دارد. فایل مانیفست ما به شکل زیر خواهد بود:
1 | { |
2 | "manifest_version": 3, |
3 | "name": "Minimalistic homepage", |
4 | "version": "1.0", |
5 | "description": "A Minimalistic homepage for my Chrome browser", |
6 | "chrome_url_overrides": { |
7 | "newtab": "home.html" |
8 | } |
9 | } |
فایل حاوی فیلدهای زیر است:
manifest_version
: این نسخه فرمت فایل مانیفست را مشخص می کند که پسوند شما از آن استفاده می کند. نسخه فعلی 3 است. نسخه مانیفست توسط Chrome تعریف شده است و مجموعه ای از ویژگی ها و قوانین موجود برای برنامه افزودنی را دیکته می کند. استفاده كردنmanifest_version: 3
تضمین می کند که برنامه افزودنی شما به آخرین استانداردها و شیوه های Chrome پایبند است.name
: این نام پسوند است.description
: این یک توضیح کوتاه در مورد پسوند است.chrome_url_overrides
: کروم، به طور پیش فرض، یک صفحه برگه جدید ارائه می دهد. باchrome_url_overrides
، به Chrome می گوییم که صفحه برگه جدید را با یک برگه سفارشی لغو می کنیم.
ساختار برنامه
ساختار برنامه شامل فایل های زیر خواهد بود:
- home.html
- styles.css
- index.js
ساختار HTML
ساختار HTML با استفاده از Bootstrap ایجاد خواهد شد. بوت استرپ یک فریم ورک فرانت اند است که به توسعه دهندگان اجازه می دهد تا وب سایت ها و برنامه ها را سریعتر بسازند.
با افزودن پیوند به فایل های CDN Bootstrap در قسمت شروع کنید section of your
home.html
فایل.
1 |
|
2 | href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" |
3 | rel="stylesheet" |
4 | integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" |
5 | crossorigin="anonymous" |
6 | /> |
سپس یک div در سمت راست بالای صفحه اضافه می کنیم. div شامل موارد زیر خواهد بود:
- آ
عنصری برای نمایش آب و هوا
- یک نماد آب و هوا
- آ
tag to display the current user’s location.
1 |
|
2 | id="weather">
|
3 | |
4 | |
5 |
The main section will consist of a Bootstrap container element with the following components:
- date and time element
- Search bar component
Create the container element that will house the elements above.
1 |
|
2 | |
3 | |
4 |
Inside the container element, let’s start by adding the date and time elements:
1 |
|
2 | |
3 | |
4 |
The tag will display the date, while the
tag will display the current time.
Next, we will have a responsive bootstrap column consisting of an input text element and a search button.
1 | |
2 | class="row justify-content-center align-items-center w-100 mt-5 pt-5" |
3 | >
|
4 | |
5 | |
6 | |
7 | class="input-group-text">
|
8 |
|
9 | src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png" |
10 | alt="Google" |
11 | height="24" |
12 | />
|
13 | |
14 | |
15 |
|
16 | type="text" |
17 | id="search" |
18 | class="form-control outline-none" |
19 | placeholder="Search the web..." |
20 | />
|
21 | |
22 | |
23 | |
24 | |
25 | |
26 |
The The last component is the random quotes component, which will be fixed at the bottom center. Inside the component, we will have a id="random-quote" class="mb-3"> Add some custom CSS such as a custom font, custom border radius to the form-control group, and custom size for the weather icon. To display the weather, we will use these 2 APIs \xa0 Let’s start by getting the weather elements: Next, create a function called در داخل یک بلوک try، با ipapi.co API تماس بگیرید، API openweather به ما امکان می دهد مکان را با استفاده از نام شهر به عنوان پارامتر دریافت کنیم، بنابراین بیایید با استفاده از نام شهر درخواستی را به API آب و هوا ارسال کنیم. در کد بالا: این از اطلاعات بالا می خواهیم دما و کد آیکون را بدست آوریم. ما به روز رسانی خواهیم کرد را به روز کنید در کد به روز شده، ما موارد زیر را انجام می دهیم: مرحله بعدی نشان دادن تاریخ و زمان فعلی است. یک تابع به نام ایجاد کنید در کد بالا موارد زیر را انجام می دهیم: برای به روز رسانی تاریخ و زمان در زمان واقعی، از آخرین قابلیت نمایش نقل قول های الهام بخش تصادفی در پایین صفحه است. آرایه ای از نقل قول ها به شکل زیر ایجاد کنید: سپس یک تابع به نام ایجاد کنید در داخل تابع، عنصر را با شناسه "random_quote" به روز می کنیم که نتیجه آن انتخاب یک نقل قول تصادفی از آرایه نقل قول و تنظیم آن به عنوان محتوای متن عنصر است. مطمئن شوید که همه شما در یک پوشه هستند. ساختار پوشه شما اکنون باید به شکل زیر باشد: بعد، به صفحه افزونه های کروم بروید. همچنین می توانید مستقیماً به chrome://extensions/ بروید. در بالا سمت راست، فعال کنید حالت توسعه دهنده. در بالا سمت چپ، روی بارگیری بدون بسته بندی را فشار دهید و پوشه حاوی تمام فایل های خود را انتخاب کنید. پس از آپلود فایل ها، پسوند در لیست افزونه های شما ظاهر می شود و صفحه اصلی شما اکنون با صفحه اصلی سفارشی جدید جایگزین می شود. در اینجا نسخه ی نمایشی است. در پایان، اکنون می دانید که چگونه یک افزونه کروم را بسازید و به کار ببرید! با این دانش، شما در موقعیتی هستید که می توانید ابزارهای سفارشی بیشتری را برای بهبود و شخصی سازی تجربه مرور خود ایجاد کنید. tag to display the random quotes.
1
2
class="fixed-bottom text-center bg-light py-2 pt-3"
3
id="quote-container"
4
>
5
6
CSS Functionality
1
@import url("https://fonts.googleapis.com/css2?family=DM+Mono:ital,wght@0,300;0,400;0,500;1,300;1,400;1,500&display=swap");
2
.input-group-text {
3
background-color: white;
4
border-radius: 30px 0 0 30px;
5
border-right: none;
6
}
7
body {
8
font-family: "DM Mono", monospace;
9
}
10
.form-control {
11
border-radius: 0 30px 30px 0;
12
border-left: none;
13
}
14
15
.weather-icon {
16
width: 60px;
17
height: 60px;
18
}
JavaScript Functionality
1
const weatherElement = document.getElementById(\'weather\');
2
const weatherIcon = document.getElementById(\'weather-icon\');
3
const locationElement = document.getElementById(\'location\');
getWeather
. در داخل این تابع، ما یک درخواست POST به API ipapi.co می دهیم تا مکان کاربر فعلی را بدست آوریم، سپس از موقعیت مکانی کاربر برای دریافت آب و هوای فعلی استفاده می کنیم.1
async function getWeather() {
2
3
const locationResponse = await fetch(\'https://ipapi.co/json/\');
4
const location = await locationResponse.json();
5
locationElement.textContent = location.city;
6
7
}
fetch(\'https://ipapi.co/json/\')
: این خط کد درخواستی را به ipapi ارسال می کندشرکت API برای بازیابی اطلاعات مکان بر اساس آدرس IP کاربر.const location = await locationResponse.json();
منتظر پاسخ می ماند و آن را به عنوان JSON تجزیه می کند.locationElement.textContent = location.city;
شهر را از داده های JSON بالا بازیابی می کند و به روز می کند textContent
عنصر مکان به شهر فعلی1
async function getWeather() {
2
try {
3
const locationResponse = await fetch(\'https://ipapi.co/json/\');
4
const location = await locationResponse.json();
5
locationElement.textContent = location.city;
6
7
const ApiKey = \'04419024fb0f20edd3f1abd06e46dd6d\';
8
const url = `https://api.openweathermap.org/data/2.5/weather?q=${location.city}&units=metric&appid=${ApiKey}`;
9
10
const response = await fetch(url);
11
const weatherData = await response.json();
12
console.log(weatherData)
13
14
} catch (error) {
15
console.error(\'Error fetching weather data:\', error);
16
locationElement.textContent = "Error fetching weather";
17
18
}
19
}
API_KEY
متغیر.const response=awaitfetch(url);
سپس، ما یک درخواست واکشی به url ساخته شده انجام می دهیم.const weatherData=awaitresponse.json();
ما پاسخ را به صورت JSON تجزیه می کنیم و شی را در متغیری به نام ذخیره می کنیم weatherData
.weatherData
وارد شده به کنسول به شکل زیر است:weatherElement
برای نشان دادن دمای فعلی و weatherIcon
عنصری برای نشان دادن url نماد آب و هوای فعلی .getWeather
تابع:1
async function getWeather() {
2
try {
3
const locationResponse = await fetch(\'https://ipapi.co/json/\');
4
const location = await locationResponse.json();
5
locationElement.textContent = location.city;
6
7
const ApiKey = \'04419024fb0f20edd3f1abd06e46dd6d\';
8
const url = `https://api.openweathermap.org/data/2.5/weather?q=${location.city}&units=metric&appid=${ApiKey}`;
9
10
const response = await fetch(url);
11
const weatherData = await response.json();
12
console.log(weatherData)
13
14
const temperature = weatherData.main.temp;
15
const weatherIconUrl = `https://openweathermap.org/img/wn/${weatherData.weather(0).icon}.png`;
16
17
weatherElement.textContent = `${Math.round(temperature)}°C`;
18
weatherIcon.src = weatherIconUrl;
19
} catch (error) {
20
console.error(\'Error fetching weather data:\', error);
21
locationElement.textContent = "Error fetching weather";
22
23
}
24
}
25
26
getWeather();
const temperature = weatherData.main.temp;
دما را از جسم آب و هوا دریافت می کند.const weatherIconUrl = `https://openweathermap.org/img/wn/${weatherData.weather(0).icon}.png`;
نشانی وب نماد آب و هوا را از نماد آب و هوای فعلی می سازد.weatherElement.textContent = `${Math.round(temperature)}°C`;
را به روز می کند weatherElement
با مقدار دمای فعلی گرد شده به نزدیکترین عدد صحیح.updateTime
، که به شکل زیر است:1
function updateTime() {
2
const now = new Date();
3
const options = {
4
weekday: "long",
5
year: "numeric",
6
month: "long",
7
day: "numeric",
8
};
9
const formattedTime = now.toLocaleTimeString("en-US", {
10
hour: "2-digit",
11
minute: "2-digit",
12
second: "2-digit",
13
});
14
currentTimeElement.textContent = ` ${formattedTime}`;
15
16
const formattedDate = now.toLocaleDateString("en-US", options);
17
currentDay.textContent = `${formattedDate} `;
18
}
const now = new Date();
تاریخ و زمان فعلی را دریافت می کند.const formattedTime = now.toLocaleTimeString("en-US"{ hour: "2-digit", minute: "2-digit", second: "2-digit"});
زمان فعلی را دریافت می کند و آن را در قالب ساعت، دقیقه و ثانیه قالب بندی می کند.currentTimeElement.textContent = ` ${formattedTime}`;
CurrentTimeElement را با زمان قالب بندی شده به روز می کند.const formattedDate = now.toLocaleDateString("en-US", { weekday: "long", year: "numeric", month: "long", day: "numeric" });
در اینجا ما از toLocaleDateString()
روشی برای قالب بندی تاریخ به رشته ای که روز کامل هفته، ماه، روز عددی ماه و سال را نشان می دهد. به عنوان مثال، یک تاریخ نمونه به این شکل خواهد بود (دوشنبه، 10 ژوئن 2024).currentDay.textContent=`${formattedDate} `;
را به روز می کند currentDay
عنصر برای نشان دادن تاریخ قالب بندی شده.setInterval
روش فراخوانی updateTime()
عملکرد بعد از هر ثانیه1
setInterval(updateTime, 1000);
2
updateTime();
1
const quotes = (
2
"The best way to get started is to quit talking and begin doing. - Walt Disney",
3
"The pessimist sees difficulty in every opportunity. The optimist sees opportunity in every difficulty. - Winston Churchill",
4
"Don’t let yesterday take up too much of today. - Will Rogers",
5
"You learn more from failure than from success. Don’t let it stop you. Failure builds character. - Unknown",
6
"It’s not whether you get knocked down, it’s whether you get up. - Vince Lombardi",
7
"If you are working on something that you really care about, you don’t have to be pushed. The vision pulls you. - Steve Jobs",
8
"People who are crazy enough to think they can change the world, are the ones who do. - Rob Siltanen",
9
"Failure will never overtake me if my determination to succeed is strong enough. - Og Mandino",
10
"Entrepreneurs are great at dealing with uncertainty and also very good at minimizing risk. That’s the classic entrepreneur. - Mohnish Pabrai",
11
"We may encounter many defeats but we must not be defeated. - Maya Angelou"
12
);
getQuote()
که شبیه این است:1
function getQuote(){
2
const quoteIndex = Math.floor(Math.random() *quotes.length);
3
const randomQuote = quotes(quoteIndex);
4
document.getElementById(\'random-quote\').textContent = randomQuote;
5
}
6
getQuote();
نحوه آپلود افزونه کروم
1
.
2
├── home.html
3
├── index.js
4
├── manifest.json
5
└── styles.css
نتیجه
منبع: https://webdesign.tutsplus.com/how-to-create-a-chrome-extension-with-vanilla-javascript--cms-108762t