chrome 공식 문서 참조
https://developer.chrome.com/docs/extensions/reference/api/scripting?hl=ko
https://developer.chrome.com/docs/extensions/develop/concepts/content-scripts?hl=ko
콘텐츠 스크립트 | Extensions | Chrome for Developers
콘텐츠 스크립트 및 Chrome 확장 프로그램에서 콘텐츠 스크립트를 사용하는 방법에 대한 설명입니다.
developer.chrome.com
chrome.scripting | API | Chrome for Developers
이 페이지는 Cloud Translation API를 통해 번역되었습니다. Switch to English chrome.scripting 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. 설명 chrome.scripting API를 사용
developer.chrome.com
문제상황
- content.js가 필요할 때만 작동되게 하고 싶다.
- content.js가 다른 url로 이동했을 때 삭제되었다가 다시 작동되어야 한다.
이 상황을 해결하기 위해 chrome.scripting 공식 문서를 찾아보았다.
chrome.scripting
chrome.scripting
- 다양한 컨텍스트에서 스크립트를 실행할 수 있다.
- executeScript
- getRegisteredContentScripts
- insertCSS
- registerContentScripts
- removeCSS
- unregisterContentScripts
- updateContentScripts
가 있다.
excuteScript와 register/unregister/get/update ContentScripts
- pratice.js에는 실행 확인을 위한 console.log가 포함되어 있다.
- 두 개를 동시에 실행시켰는데 exceuteScript만 실행되었다.
excuteScript
- executeScript에서 삽입된 함수는 원래 함수 자체가 아니라 참조된 함수의 사본이다.
- 따라서 함수의 본문은 자체적으로 포함되어야 한다.
- 함수 외부의 변수를 참조하면 콘텐츠 ReferenceError가 발생한다.
registerContentScripts
- 말 그대로 script들을 등록하는 함수
- 확장 프로그램 자체에 script를 등록하는 것 같다.
unregisterContentScripts
- 등록한 함수들 다시 제거
getRegisteredContentScripts
- 등록된 Content Scripts 목록 가져오기
updateContentScripts
- ContentScripts 업데이트 기능
insertCSS와 removeCSS
insertCSS
- CSS 파일이나 string 동적으로 등록할 수 있다.
removeCSS
- insertCSS와 반대로 동적으로 등록된 CSS 삭제
결론
해결된 문제상황
- content.js가 필요할 때만 작동되게 하고 싶다.
- content.js가 다른 url로 이동했을 때 삭제되었다가 다시 작동되어야 한다.
- excuteScript 써서 1번 문제를 해결했는데, 다른 프레임에 갔다가 다시 돌아오면 script가 중복 처리 되어버렸다(2번 문제).
- 2번 문제는 그냥 if문 써서 감싸주는 거로 해결됐다.
const already = document.getElementByClassName('클래스 네임');
if(already.length ==== null ){
// 실행될 코드
}
'chrome-extension > 첫 chrome extension 개발' 카테고리의 다른 글
| chrome.webNavigation (1) | 2024.02.03 |
|---|