이 게시물에서는 콘텐츠 스크립트와 이를 사용하여 웹 페이지를 변경하는 방법에 초점을 맞출 것입니다.
살펴볼 주요 개념은 다음과 같습니다.
예
이 게시물의 예에서는 초기 샘플 확장에 기능을 계속 추가하겠습니다. 콘텐츠 스크립트를 사용하여 현재 활성화 된 페이지의 오른쪽 하단에 알림을 표시합니다.
또한 이 시리즈에서 이전에 배운 내용에 의존 할 것입니다. 명령은 알림을 트리거하여 백그라운드 스크립트에서 처리합니다. 마지막으로 백그라운드 스크립트는 콘텐츠 스크립트에 메시지를 보내 화면 오른쪽 하단에 페이지 제목을 표시하는 알림을 활성화합니다.
콘텐츠 스크립트 정보
코딩하자!
1. 새 명령 만들기
이 시리즈의 이전 게시물에서 예제 확장에 두 개의 명령을 추가했습니다. 이제 우리는 세 번째를 추가 할 것입니다. 이를 위해 먼저 명령을 정의하고 manifest.json 파일에 제안 된 바로 가기를 정의합니다.
{
"manifest_version": 2,
"name": "Acho, where are we?",
// ...
"commands": {
"bark": {
"suggested_key": {
"default": "Alt+Shift+3"
},
"description": "Makes Acho bark the title at the bottom right of the current page."
},
// .... Other commands
}
}
이제 onCommand 이벤트를 수신하여 명령을 처리해야 합니다. 이것은 백그라운드 스크립트에서 수행되어야 합니다.
// background.js
chrome.commands.onCommand.addListener(function (command) {
switch (command) {
case 'bark':
barkTitle();
break;
default:
console.log(`Command ${command} not found`);
}
});
function barkTitle() {
const query = { active: true, currentWindow: true };
chrome.tabs.query(query, (tabs) => {
chrome.tabs.sendMessage(tabs[0].id, {
tabTitle: tabs[0].title
});
});
}
따라서 bark 명령이 실행되면 현재 활성화 된 탭의 제목을 나타내는 메시지를 보냅니다. 이제 콘텐츠 스크립트는 해당 메시지를 듣고 알림을 표시해야 합니다.
메시지 정보 : 콘텐츠 스크립트는 확장의 컨텍스트가 아니라 웹 페이지의 컨텍스트에서 실행됩니다. 확장 프로그램과 통신 할 방법이 필요합니다. 메시지를 사용하여 그렇게 할 수 있습니다.
2. 콘텐츠 스크립트 등록
콘텐츠 스크립트를 만들기 위해 가장 먼저 해야 할 일은 (예, 짐작할 수 있습니다!) manifest.json 파일에 추가하는 것입니다.
{
"manifest_version": 2,
"name": "Acho, where are we?",
// ...
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"css": ["content.css"]
}
],
"web_accessible_resources": [
"images/icon32.png"
],
}
3. 알림 표시
content.js에 로직을 추가하는 것으로 시작하겠습니다.
// Notification body.
const notification = document.createElement("div");
notification.className = 'acho-notification';
// Notification icon.
const icon = document.createElement('img');
icon.src = chrome.runtime.getURL("images/icon32.png");
notification.appendChild(icon);
// Notification text.
const notificationText = document.createElement('p');
notification.appendChild(notificationText);
// Add to current page.
document.body.appendChild(notification);
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
const notification = document.getElementsByClassName('acho-notification')[0];
const notificationText = notification.getElementsByTagName('p')[0];
notificationText.innerHTML = request.tabTitle;
notification.style.display = 'flex';
setTimeout(function () {
notification.style.display = 'none';
}, 5000);
return true;
});
이제 이전 코드를 더 자세히 살펴 보겠습니다.
이 처음 15 줄은 로드 된 모든 페이지가 알림 구조를 갖도록 합니다. 마지막으로 알림을 표시하기 위해 chrome.runtime.onMessage에 대한 리스너를 추가했습니다. 해당 코드를 살펴 보겠습니다.
큰! 거의 완료되었습니다. content.css 파일의 알림에 몇 가지 스타일을 추가해 보겠습니다.
.acho-notification {
background-color: white;
border: rgb(242, 105, 77) 1px solid;
border-radius: 5px;
font-size: medium;
width: 320px;
display: none;
padding: 8px;
position: fixed;
bottom: 30px;
right: 30px;
align-items: center;
}
.acho-notification > img {
margin-right: 12px;
}
Done!
그리고 그게 다야! 다음은 사용자가 Alt + Shift + 3을 눌렀을 때 알림이 표시되는 방식입니다.
저장소
이 저장소를 모든 Chrome 확장 프로그램 예제로 업데이트하고 있습니다.
https://dev.to/paulasantamaria/chrome-extensions-making-changes-to-a-web-page-1n5f
등록된 댓글이 없습니다.