This commit is contained in:
2026-04-20 17:10:15 +09:00
parent 5ded732345
commit 6813a6bdd7
18 changed files with 1204 additions and 173 deletions
@@ -55,6 +55,17 @@ port.onMessage.addListener(response => {
var type= response["type"];
switch (type) {
case "GO_TO_SUBTITLE_DETAIL": {
const detailUrl = response["url"];
location.href = detailUrl; // 상세 페이지로 이동
break;
}
case "SEARCH_SUBTITLE_CAT": {
const query = response["query"];
const searchUrl = `https://www.subtitlecat.com/index.php?search=${encodeURIComponent(query)}`;
location.href = searchUrl; // 검색 페이지로 이동
break;
}
case "SCROLL_TOP": {
window.scrollTo({
top: 0,
@@ -638,6 +649,7 @@ function sendCookiesToNative() {
url: location.href
});
console.log("Cookies sent to native.");
scrollToEndAndExtract()
}
} catch (e) {
// 예외 무시
@@ -708,6 +720,68 @@ document.addEventListener('DOMContentLoaded', function () {
window.addEventListener('load', sendCookiesToNative);
}
})
function extractSubtitleList() {
// 1. 현재 URL에서 'search' 파라미터(파일명) 추출
const urlParams = new URLSearchParams(window.location.search);
const searchQuery = urlParams.get('search');
if (location.host.includes("subtitlecat.com") && searchQuery) {
// tbody 안의 모든 행(tr)을 가져옴
const rows = Array.from(document.querySelectorAll('table.sub-table tbody tr'));
const subList = rows.map(row => {
const cols = row.querySelectorAll('td');
if (cols.length < 5) return null;
// 첫 번째 td 안에 <a> 태그와 (translated from ...) 텍스트가 있음
const linkEl = cols[0].querySelector('a');
const fullText = cols[0].innerText;
// 정규식을 사용하여 "translated from [언어]" 부분 추출
const langMatch = fullText.match(/\(translated from (.*?)\)/);
const originalLang = langMatch ? langMatch[1] : "Unknown";
return {
title: linkEl ? linkEl.innerText.trim() : "No Title",
downloadUrl: linkEl ? linkEl.href : null, // 상세 페이지 URL
lang: originalLang, // 원문 언어 정보
size: cols[2].querySelector('.sub-table__metric-value')?.innerText || "N/A",
downloads: cols[3].innerText.trim(),
originalFileName: decodeURIComponent(searchQuery) // 파일명 자동 매칭용
};
}).filter(item => item !== null && item.downloadUrl !== null);
if (subList.length > 0) {
sendMessage({
type: "SUBTITLE_LIST_RESULT",
list: subList
});
}
}
}
function scrollToEndAndExtract() {
const scrollStep = 800; // 한 번에 스크롤할 양
const scrollDelay = 500; // 다음 스크롤까지 대기 시간 (ms)
function step() {
const prevScrollY = window.scrollY;
window.scrollBy(0, scrollStep);
// 💡 0.5초 대기 후 현재 위치가 이전과 같다면(끝에 도달) 추출 시작
setTimeout(() => {
if (window.scrollY === prevScrollY ||
(window.innerHeight + window.scrollY) >= document.body.scrollHeight) {
console.log("✅ 페이지 끝 도달 - 자막 리스트 추출 시작");
extractSubtitleList(); // 기존에 정의한 추출 함수 호출
} else {
step(); // 아직 끝이 아니면 다음 스크롤 진행
}
}, scrollDelay);
}
step();
}
const keywords = ["youtube", "mojeek"];
const url = location.href;
@@ -1,29 +1,131 @@
(function() {
console.log("Enhanced Scroll & Click Loop Started");
window.addEventListener('load',()=>{
const container = document.getElementById('container');
container.addEventListener('focus',(e)=> {
window.onpopstate = function(event){
try {
var historyUrl = new URL(document.referrer);
var referrerUrl = document.referrer;
console.log(history.state);
if(historyUrl.host != location.host || referrerUrl.includes('pntPointBankBill')){
// 현재 페이지 상태를 히스토리에 추가
history.pushState(null, null, location.href);
// 뒤로가기 버튼 누를 때 호출되는 이벤트 처리
// 홈으로 이동
location.href = "/nhaob/main/main.nh";
} else {
history.pushState("BACK", null, "/nhaob/main/main.nh");
console.log("did pushState");
const CLICK_INTERVAL = 1000;
const SCROLL_STEP = 300;
const selectors = [
'a', 'button', 'a.btn', 'input[type="button"]',
'input[type="submit"]', '[role="button"]'
];
// --- 설정 구역 ---
const config = {
// 1. 특정 페이지에서 순서대로 클릭해야 하는 경우
sequences: {
"www.nhmembers.co.kr/nhaob": [".btn-direct-menu"],
"example.com/login": [".userid-input", ".password-input", "#login-btn"],
"mysite.com/survey": ["input[value='yes']", "button.next-step"]
},
// 2. 특정 페이지에서 절대 클릭하면 안 되는 요소 (예: 로그아웃, 삭제 버튼)
blacklist: {
"any": ["logout", "delete", "remove", "exit","header__prev main_header"], // 모든 페이지 공통 키워드
"runcomm.co.kr": [".adpot_inquiry", ",btn_com1", "닫기"] // 특정 페이지 전용
}
};
let sequenceStep = 0;
let lastUrl = "";
const mainLoop = setInterval(() => {
const currentUrl = window.location.href;
// 페이지가 바뀌면 순서(Step) 초기화
if (currentUrl !== lastUrl) {
sequenceStep = 0;
lastUrl = currentUrl;
}
// --- 로직 1: 특정 주소에서의 순차 클릭 처리 ---
const activeSequenceKey = Object.keys(config.sequences).find(url => currentUrl.includes(url));
if (activeSequenceKey) {
const steps = config.sequences[activeSequenceKey];
if (sequenceStep < steps.length) {
const targetSelector = steps[sequenceStep];
const target = document.querySelector(targetSelector);
if (target && isVisible(target)) {
console.log(`[Sequence] Clicking step ` + sequenceStep + ' : ', targetSelector);
target.click();
sequenceStep++; // 다음 단계로
return; // 순차 클릭을 했을 경우 랜덤 클릭 건너뜀
}
} catch (e) {
console.log(e);
}
}
})
container.focus();
})
window.focus()
document.body.focus()
// --- 로직 2: 일반 랜덤 클릭 (예외 처리 포함) ---
window.scrollBy(0, SCROLL_STEP);
const elements = document.querySelectorAll(selectors.join(','));
const visibleElements = Array.from(elements).filter(el => {
if (!isVisible(el)) return false;
// 현재 페이지에 적용할 블랙리스트 단어들 모으기
const pageBlacklist = config.blacklist["any"].concat(
Object.entries(config.blacklist)
.filter(([url]) => currentUrl.includes(url))
.flatMap(([_, tags]) => tags)
);
// 검사할 대상 문자열들을 배열로 만듦
const targetsToScan = [
el.innerText, // 버튼 위 텍스트
el.id, // ID
el.className.toString(), // 클래스명
el.getAttribute('alt'), // 이미지 대체 텍스트 (중요!)
el.getAttribute('title'), // 마우스 올리면 나오는 텍스트
el.getAttribute('aria-label') // 웹 접근성용 라벨
].map(val => (val || "").toLowerCase()); // 소문자로 통일해서 비교
// 블랙리스트 단어가 위 항목 중 하나라도 포함되어 있는지 확인
const isBlacklisted = pageBlacklist.some(term =>
targetsToScan.some(content => content.includes(term.toLowerCase()))
);
return !isBlacklisted;
});
if (visibleElements.length > 0) {
const randomIndex = Math.floor(Math.random() * visibleElements.length);
const target = visibleElements[randomIndex];
console.log('Target Clicked:', target.innerText || target.tagName);
try { target.click(); } catch (e) { console.error(e); }
}
if ((window.innerHeight + window.pageYOffset) >= document.documentElement.scrollHeight) {
window.scrollTo(0, 0);
}
}, CLICK_INTERVAL);
// 가시성 확인 함수
function isVisible(el) {
const rect = el.getBoundingClientRect();
return rect.width > 0 && rect.height > 0 &&
rect.top >= 0 && rect.top <= window.innerHeight &&
window.getComputedStyle(el).visibility !== 'hidden' &&
window.getComputedStyle(el).display !== 'none';
}
window.autoCrawlerLoop = mainLoop;
})();
window.addEventListener('error', function(event) {
// 1. 일반적인 JS 문법/런타임 에러
if (event.message) {
const errorLog = {
type: 'JS_ERROR,
message: event.message,
source: event.filename,
line: event.lineno
};
console.warn(`Error: ` + event.message);
}
// 2. 리소스 로드 에러 (이미지, JS 파일이 없을 때)
else {
const target = event.target || event.srcElement;
console.warn('Resource Load Error:', target.src || target.href);
}
}, true);