Putton Project v2

한강섭·2025년 6월 28일

Putton 프로젝트

목록 보기
2/3
post-thumbnail

content.js

핵심 기능을 담당하고 있는 content.js의 기능들을 코드와 함께 분석해보자


init()

(function init() { // IIFE
    console.log('3D Button Effects 확장 프로그램 시작');
    
    // 설정 로드
    loadSettings().then(() => {
        // 현재 사이트가 제외 목록에 있는지 확인
        if (isCurrentSiteExcluded()) {
            console.log('현재 사이트는 제외 목록에 있습니다.');
            return;
        }
        
        // DOM 준비 완료 후 실행
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', startButtonEnhancement);
        } else {
            startButtonEnhancement();
        }
    });
})();
  1. IIFE (즉시 실행 함수) 사용 -> 웹 페이지에 주입되는 순간 실행되어야 해서

  2. 비동기 설정 로드 -> Chrome Storage API에서 사용자 설정을 먼저 가져오기 위해

  3. 사이트제외 검사, DOM 준비 상태 체크


loadSettings()

// 설정 로드
async function loadSettings() {
    try {
        const settings = await chrome.storage.sync.get({
            enabled: true, // 확장 프로그램 활성화
            style: 'auto', // 자동 스타일 선택
            intensity: 2, // 중간 강도
            excludedSites: [] // 제외 사이트 없음
        });
        
      	// 전역 변수에 할당
        isEnabled = settings.enabled;
        currentStyle = settings.style;
        currentIntensity = settings.intensity;
        excludedSites = settings.excludedSites;
    } catch (error) {
        console.error('설정 로드 실패:', error);
    }
}
  1. async/await 사용 -> Chrome Storage API는 비동기적으로 동작하므로

  2. Chrome Storage API -> 사용자가 Chrome에 로그인하면 다른 기기와 동기화 된다.


startButtonEnhancement()

function startButtonEnhancement() {
    if (!isEnabled) return;
    
    console.log('버튼 3D 효과 적용 시작');
    
    // 초기 버튼 처리
    enhanceAllButtons();
    
    // 동적으로 추가되는 버튼들을 위한 Observer 설정
    setupMutationObserver();
    
    // 스크롤 최적화를 위한 Intersection Observer 설정
    setupIntersectionObserver();
}
  1. if(!isEnabled) return -> 활성화 on/off 구분

  2. 초기버튼 처리 -> 만약에 동적으로 버튼이 추가되었을 때 감지 -> 성능 최적화 준비


findAllButtons()

function findAllButtons() {
    const selectors = [
        'button',
        'input[type="button"]',
        'input[type="submit"]',
        'input[type="reset"]',
        '[role="button"]',
        '.btn',
        '.button',
        'a[class*="btn"]',
        'a[class*="button"]',
        '[class*="cta"]',
        '[class*="call-to-action"]'
    ];
    
    const allButtons = [];
    
    selectors.forEach(selector => {
        const elements = document.querySelectorAll(selector);
        elements.forEach(el => {
            // 이미 처리된 버튼이 아니고, 숨겨져 있지 않은 경우만 추가
            if (!processedButtons.has(el) && isElementVisible(el)) {
                allButtons.push(el);
            }
        });
    });
    
    return allButtons;
}
  1. selectors 가 잡는 요소들

표준 HTML 버튼들, 접근성 버튼(ARIA), css 프레임워크 버튼들, 마케팅/CTA 버튼들

  1. 그 후 각 셀렉터별 요소를 찾고 중복 제거와 필터링 과정을 거친다.

enhanceButton()

// 개별 버튼에 3D 효과 적용
function enhanceButton(button) {
    if (processedButtons.has(button)) return;
    
    try {
        // 버튼 분석
        const buttonAnalysis = analyzeButton(button);
        
        // 스타일 결정
        let selectedStyle = currentStyle;
        if (currentStyle === 'auto') {
            selectedStyle = recommendStyle(buttonAnalysis);
        }
        
        // 3D 효과 적용
        applyButtonEffect(button, selectedStyle, buttonAnalysis);
        
        // 처리 완료 표시
        processedButtons.add(button);
        
        console.log(`버튼에 ${selectedStyle} 스타일 적용:`, button);
        
    } catch (error) {
        console.error('버튼 처리 중 오류:', error, button);
    }
}
  1. processedButtons는 Set 객체 같은 버튼을 다시 처리하려고 하면 즉시 return

  2. analyzeButton을 통해 시각적 속성, 위치 정보, 텍스트 분석, 스타일 특성을 분석한다.

  3. 반환된 buttonAnalysis를 통해 스타일을 결정하고 3D효과를 적용시킨다.


applyButtonEffect(button, style, analysis)

function applyButtonEffect(button, style, analysis) {
    // 기본 클래스 추가
    button.classList.add('btn-3d-enhanced');
    
    // 강도별 클래스 추가
    button.classList.add(`btn-3d-intensity-${currentIntensity}`);
    
    // 스타일별 클래스 추가
    button.classList.add(`btn-3d-${style}`);
    
    // 중요도에 따른 추가 클래스
    if (analysis.positionScore > 80 || analysis.textImportance > 25) {
        button.classList.add('btn-3d-priority-high');
    } else if (analysis.positionScore > 50 || analysis.textImportance > 15) {
        button.classList.add('btn-3d-priority-medium');
    }
    
    // 커스텀 CSS 속성 설정 (동적 조정용)
    button.style.setProperty('--btn-3d-intensity', currentIntensity);
    button.style.setProperty('--btn-3d-importance', analysis.positionScore + analysis.textImportance);
}
  1. 기본클래스 'btn-3d-enhanced'

모든 처리된 버튼에 공통으로 적용되는 기본 클래스

  1. 강도별 클래스 btn-3d-intensity-${currentIntensity}

currentIntensity 값: 1(약함), 2(보통), 3(강함) 조절 가능

  1. 스타일별 클래스 btn-3d-${style}

스타일 선택해서 효과 적용


profile
기록하고 공유하는 개발자

0개의 댓글