티스토리 뷰
크롬 확장프로그램 background.js에서현재 열려있는 탭의 페이지의 dom에 접근해서 특정 값 popup.html로 에 div를 추가해서 전달
krfreedevlife 2024. 5. 24. 10:46이 코드는 다음과 같은 작업을 수행합니다:
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로 접근해야하는 점 때문에
'프로그래밍' 카테고리의 다른 글
모바일에서 이미지클릭만 되고 다운받기는 안되게 하고싶을때 (0) | 2024.10.22 |
---|---|
쇼피파이 api로 주문내역에서 통관번호 가져오기,송장번호 업데이트. (0) | 2024.08.27 |
LSPosed와 Magisk는 Android 기기에서 시스템 및 앱의 동작을 수정하는 데 사용되는 도구, 멀티앱 용도에 사용 (0) | 2024.05.19 |
fullcalendar 에서 통계 만들기 . events 발생후 (0) | 2024.05.09 |
안드로이드폰 개발자모드로 디버깅 하는 방법 fullcalendar select 관련 (0) | 2024.05.06 |
- Total
- Today
- Yesterday
- 클라우드플레어
- 파이썬
- 아파치
- 오토셋
- 회원가입
- xe
- 셀레니움
- 유튜브
- php8
- lsposed
- Apache
- 제로보드
- 파이선
- 에러
- 텔레그램
- 텔레그램봇
- .htaccess
- 루팅
- 아미나
- 그누보드5
- Fullcalendar
- 멀티계정
- php
- Cloudflare
- python
- 그누보드
- Magisk
- 당근
- 윈도우
- SSL
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |