크롬 확장프로그램 background.js에서현재 열려있는 탭의 페이지의 dom에 접근해서 특정 값 popup.html로 에 div를 추가해서 전달
이 코드는 다음과 같은 작업을 수행합니다:
chrome.runtime.onMessage.addListener를 사용하여 메시지 리스너를 등록합니다. 이 리스너는 popup.html에서 보낸 메시지를 받아 처리합니다.
메시지 타입이 'getLinksFromCurrentTab'일 경우 실행됩니다.
현재 활성화된 탭을 가져옵니다.
chrome.scripting.executeScript를 사용하여 현재 탭의 DOM에 접근하고, 특정 CSS 선택자('.specific-css-class')를 가진 요소의 href 값을 가져옵니다.
가져온 링크 정보를 sendResponse를 통해 popup.html에 전달합니다.
이 코드를 background.js에 추가하면 popup.html에서 링크 정보를 받아와 표시할 수 있습니다.
chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {
if (request.type === 'getLinksFromCurrentTab') {
try {
// 현재 활성화된 탭을 가져옵니다.
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
// 탭의 DOM에 접근하여 특정 CSS를 가진 요소의 href 값을 가져옵니다.
const links = await chrome.scripting.executeScript({
target: { tabId: tab.id },
function: () => {
const targetElements = document.querySelectorAll('.specific-css-class');
return Array.from(targetElements).map(elem => elem.href);
},
});
// 가져온 링크 정보를 popup.html에 전달합니다.
sendResponse({ links: links[0].result });
} catch (error) {
console.error('Error getting links from current tab:', error);
sendResponse({ error: error.message });
}
return true; // 비동기 응답을 보내기 위해 true 반환
}
});
이 코드는 다음과 같은 작업을 수행합니다:
DOMContentLoaded 이벤트 리스너를 등록하여 DOM이 로드되면 실행됩니다.
getLinksFromCurrentTab 함수를 정의합니다. 이 함수는 background.js에 'getLinksFromCurrentTab' 메시지를 보내서 현재 탭의 링크 정보를 가져옵니다.
메시지를 보내기 위해 chrome.runtime.sendMessage를 사용합니다. 이때 메시지 객체에 type 속성을 추가하여 background.js에서 메시지를 구분할 수 있도록 합니다.
메시지 응답을 받아 링크 정보를 처리합니다. 예를 들어 콘솔에 출력하거나 popup.html에 표시할 수 있습니다.
DOM 로드 시 getLinksFromCurrentTab 함수를 호출하여 현재 탭의 링크 정보를 가져옵니다.
이 코드를 popup.js에 추가하면 background.js에서 링크 정보를 가져와 popup.html에 표시할 수 있습니다.
document.addEventListener('DOMContentLoaded', () => {
// DOM이 로드되면 실행됩니다.
// 메시지를 보내는 함수
async function getLinksFromCurrentTab() {
try {
// 메시지 보내기
const response = await chrome.runtime.sendMessage({ type: 'getLinksFromCurrentTab' });
if (response.error) {
console.error('Error getting links from current tab:', response.error);
return;
}
// 받은 링크 정보를 처리하는 코드 작성
console.log('Links from current tab:', response.links);
// popup.html에 링크 정보를 표시하는 코드 작성
const linksContainer = document.getElementById('links-container');
response.links.forEach(link => {
const linkElement = document.createElement('div');
linkElement.textContent = link;
linksContainer.appendChild(linkElement);
});
} catch (error) {
console.error('Error sending message to background script:', error);
}
}
// DOM 로드 시 getLinksFromCurrentTab 함수 호출
getLinksFromCurrentTab();
});
response 객체가 정의되었는지 확인하고, 그 후에 response.links와 response.error를 확인합니다.
response.links가 있는 경우 링크 정보를 처리합니다.
response.error가 있는 경우 오류 메시지를 콘솔에 출력합니다.
예상하지 못한 응답이 온 경우 별도로 처리합니다.
이렇게 수정하면 응답 객체가 정의되지 않은 경우에 오류가 발생하지 않을 것입니다. 문제가 지속되는 경우 background.js 코드를 다시 한번 확인해 보세요.
document.addEventListener('DOMContentLoaded', () => {
// DOM이 로드되면 실행됩니다.
// 메시지를 보내는 함수
async function getLinksFromCurrentTab() {
try {
// 메시지 보내기
const response = await chrome.runtime.sendMessage({ type: 'getLinksFromCurrentTab' });
// 응답 처리
if (response && response.links) {
console.log('Links from current tab:', response.links);
// popup.html에 링크 정보를 표시하는 코드 작성
const linksContainer = document.getElementById('links-container');
response.links.forEach(link => {
const linkElement = document.createElement('div');
linkElement.textContent = link;
linksContainer.appendChild(linkElement);
});
} else if (response && response.error) {
console.error('Error getting links from current tab:', response.error);
} else {
console.error('Unexpected response from background script:', response);
}
} catch (error) {
console.error('Error sending message to background script:', error);
}
}
// DOM 로드 시 getLinksFromCurrentTab 함수 호출
getLinksFromCurrentTab();
});
최초에는 element로 바로 접근이 되지만 스크롤을 하는등의 변화가 생기면 변화된 element로 접근해야하는 점 때문에