Это было намного быстрее, чем я думал, что это будет.
Генерировать проект
Я использовал Йоман генерировать леса. Сделайте папку проекта и запустите:
npm install -g yo generator-web-extension yo web-extension
Много вариантов, но я бы пошел с минимумом на данный момент. Одна вещь, которую я сделал, была кнопкой в расширении.
Тогда иди к вашему хромированные расширения и нажмите «Загрузить распакованный». Найти Dist каталог, который был сгенерирован, и вы должны быть расширение Dev в Chrome готовы к работе. Нажмите на кусок головоломки в области расширений и выкрепите свое расширение.
Теперь мы можем уволить наблюдателя и начать кодирование, получив живое обновление:
npm run dev chrome
Структура кода
Там небольшое всплывающее окно, когда вы нажмете расширение. Подумайте об этом, так как это собственная отдельная веб-страница. На самом деле, вы можете щелкнуть правой кнопкой мыши расширение и «проверьте» так же, как это веб-страница. Это где вы увидите все console.log для добавочных бит.
Мы будем вводить супер простой таймер на страницу. Для этого расширение необходимо отправить сообщение на страницу.
Перейти к приложение/страницы/popup.html и добавьте кнопку с классом Timerbutton Отказ
Теперь посмотрите в /приложение/сценарии И вы увидите три файла, два мы будем трогать:
popup.js : Это для кода, который работает внутри расширения «Страница»
contentscript.js : Это для кода, который работает на странице, пользователь в настоящее время включен
Поэтому нам нужно отправить сообщение от popup.js к contentscript.js Чтобы вызвать впрыск таймера на странице.
popup.js :
document.querySelector('.timerButton').addEventListener('click', addTimer);
function addTimer() {
browser.tabs
.query({
active: true,
currentWindow: true,
})
.then(tabs => {
browser.tabs
.sendMessage(tabs[0].id, {
timerMessage: `create`,
})
.then(response => {
console.log({response});
})
.catch(({message}) => console.error('error', message));
});
}
После того, как мы нажмем на страницу, мы сделаем все материалы таймера, включая впрыскивание некоторых HTML на странице, которая имеет какую-то хаковую драгкость:
const SECOND = 1000;
const MINUTE = SECOND * 60;
class Timer {
timerHtmlHandle;
timerInterval;
originalTime;
currentTime;
startTimer() {
this.timerInterval = setInterval(this.tick.bind(this), SECOND);
}
stopTimer() {
clearInterval(this.timerInterval);
this.timerInterval = null;
}
toggleTimer() {
this.timerInterval ? this.stopTimer() : this.startTimer();
}
resetTimer(seedTime = prompt('Enter Timer Minutes') * MINUTE) {
this.stopTimer();
this.currentTime = this.originalTime = seedTime;
this.tick();
}
refreshTimer() {
this.stopTimer();
this.currentTime = this.originalTime;
this.tick();
}
addMinute() {
this.currentTime = this.currentTime + MINUTE;
this.tick();
}
tick() {
const timerText = `${Math.floor(this.currentTime / MINUTE)}:${`${
(this.currentTime % MINUTE) / SECOND
}`.padStart(2, '0')}`;
this.timerHtmlHandle.innerText = timerText;
this.currentTime = this.currentTime - SECOND;
if (this.currentTime < 0) {
this.stopTimer();
} else if (this.currentTime < MINUTE * 2) {
// two minute warning
this.timerHtmlHandle.style.color = '#f5b20a';
} else if (this.currentTime < MINUTE) {
// one minute warning
this.timerHtmlHandle.style.color = '#da521f';
}
}
}
const duhlTimer = new Timer();
const addTimer = () => {
const timerHtml = `
0:00
`;
document.body.insertAdjacentHTML('afterbegin', timerHtml);
duhlTimer.timerHtmlHandle = document.querySelector('.ext-timer');
document
.querySelector('.duhl-timer .refreshTimer')
.addEventListener('click', () => duhlTimer.refreshTimer());
document
.querySelector('.duhl-timer .addMinute')
.addEventListener('click', () => duhlTimer.addMinute());
document
.querySelector('.duhl-timer .resetTimer')
.addEventListener('click', () => duhlTimer.resetTimer());
document
.querySelector('.duhl-timer .toggleTimer')
.addEventListener('click', () => duhlTimer.toggleTimer());
document.querySelector('.duhl-timer').addEventListener('dragend', e => {
console.log(e);
e.target.style.top = `${e.pageY}px`;
e.target.style.left = `${e.pageX}px`;
});
};
browser.runtime.onMessage.addListener((req, sender, sendResponse) => {
// only one timer for you!
if (duhlTimer && duhlTimer.timerHtmlHandle) {
return;
}
addTimer();
// reflow before starting things or it gets wonky
setTimeout(() => {
duhlTimer.resetTimer(5 * MINUTE);
});
});
Ну наконец то Связанные contentscript.csss.
.duhl-timer {
padding: 0 4px;
position: absolute;
z-index: 10000000;
top: 0;
left: 0;
background: rgba(0, 0, 0, 0.8);
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3);
border: 1px solid #fff;
border-radius: 12px;
color: #fff;
}
.duhl-timer .drag {
position: absolute;
top: 0;
left: 0;
width: 16px;
height: 16px;
border-radius: 12px 0 2px 0;
background: repeating-linear-gradient(
to bottom,
#666,
#666 2px,
#333 2px,
#333 4px
);
cursor: move;
}
.duhl-timer .ext-timer {
font-size: 3rem;
line-height: 3rem;
text-align: center;
}
.duhl-timer button {
padding: 2px 6px;
border: none;
background: none;
border-radius: 4px;
}
.duhl-timer button:hover {
cursor: pointer;
background: rgba(255, 255, 255, 0.1);
}
.duhl-timer button:active {
background: rgba(255, 255, 255, 0.2);
}
И это мой плагин впрыска таймера!
Src.
Оригинал: “https://dev.to/danieluhl/my-first-chrome-plugin-389c”