caps_enhancer/js/content.js
2026-03-23 14:02:46 +03:00

170 lines
7.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// ==================== ГЛАВНЫЙ ФАЙЛ ====================
(function() {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', waitForConfigAndInit);
} else {
waitForConfigAndInit();
}
// Ожидание загрузки конфигурации перед инициализацией
function waitForConfigAndInit() {
const core = window.VideoIPRedirect;
if (!core) {
console.error('[CAPS_Enhancer] ❌ CORE не загружен!');
return;
}
const debugLog = (msg, ...args) => core.debugLog('content', msg, ...args);
// Если конфигурация уже загружена, запускаем инициализацию
if (core.configReady) {
debugLog('⚙️ Конфигурация готова, запуск инициализации...');
init();
} else {
// Иначе ждём события о готовности конфигурации
debugLog('⏳ Ожидание загрузки конфигурации...');
document.addEventListener('VideoIPRedirect:ConfigReady', () => {
debugLog('⚙️ Конфигурация загружена, запуск инициализации...');
init();
}, { once: true });
// Таймаут на случай, если событие не сработает
setTimeout(() => {
if (!core.configReady) {
debugLog('⚠️ Таймаут ожидания конфигурации, запуск с настройками по умолчанию...');
init();
}
}, 2000);
}
}
function init() {
const core = window.VideoIPRedirect;
const debugLog = (msg, ...args) => core.debugLog('content', msg, ...args);
const disabledSites = core.CONFIG.disabledSites || [];
const hostname = window.location.hostname || '';
if (disabledSites.length && disabledSites.includes(hostname)) {
debugLog('⏹ Расширение отключено на этом сайте:', hostname);
return;
}
debugLog('========== ЗАПУСК ==========');
debugLog('DOM загружен, инициализация...');
debugLog('📋 Текущая конфигурация:', core.CONFIG);
const pageType = core.checkPageType();
// Замена логотипа CleverPark на caps.svg (если включено). Лого может появиться позже (SPA), поэтому повторяем попытки + наблюдатель.
const LOGO_SELECTOR = 'img[src*="cleverpark.svg"], img[src*="cleverpark"], img[alt*="CLEVER PARK"], img[alt*="CLEVER"]';
const replaceLogoEnabled = core.CONFIG.replaceLogo !== false;
const hasGetURL = typeof chrome !== 'undefined' && chrome.runtime && typeof chrome.runtime.getURL === 'function';
function tryReplaceLogo(from) {
if (!replaceLogoEnabled || !hasGetURL) return false;
const logo = document.querySelector(LOGO_SELECTOR);
if (logo && !logo.dataset.capsReplaced) {
logo.dataset.capsReplaced = '1';
logo.src = chrome.runtime.getURL('icons/caps.svg');
debugLog('🖼️ [LOGO] Заменён на caps.svg', from ? '(' + from + ')' : '');
return true;
}
return false;
}
if (replaceLogoEnabled && hasGetURL) {
debugLog('🖼️ [LOGO] Включена замена, селектор:', LOGO_SELECTOR);
tryReplaceLogo('init');
[400, 1000, 2500].forEach((ms, i) => {
setTimeout(() => { tryReplaceLogo('retry-' + (i + 1)); }, ms);
});
const logoObserver = new MutationObserver(() => {
if (tryReplaceLogo('observer')) logoObserver.disconnect();
});
if (document.body) {
logoObserver.observe(document.body, { childList: true, subtree: true });
setTimeout(() => logoObserver.disconnect(), 10000);
}
}
// ПРИОРИТЕТ 1: Обработка страниц noVNC (переадресация или кнопка)
if (pageType.isNoVNCPage && core.NoVNCRedirect) {
const mode = core.CONFIG.novnc.mode;
debugLog(`🖥️ Обнаружена страница noVNC, режим: ${mode}`);
const handled = core.NoVNCRedirect.handleNoVNCPage();
// Если режим redirect, прерываем инициализацию (будет переадресация)
// Если режим button, продолжаем работу (только добавили кнопку)
if (mode === 'redirect' && handled) {
return;
}
}
// ПРИОРИТЕТ 2: Автологин на странице входа
if (core.AutoLogin && core.AutoLogin.isLoginPage()) {
debugLog('🔐 Обнаружена страница логина');
core.AutoLogin.tryAutoLogin();
// Продолжаем инициализацию (не прерываем)
}
if (!pageType.hasAppMarker) {
debugLog('⏹ Не CLEVER PARK, отключаемся');
return;
}
// Настраиваем Escape
if (core.CloseHandler) {
core.CloseHandler.setupEscapeHandler();
}
// Видео страница
if (pageType.isVideoPage && core.VideoWindow) {
debugLog('🎬 ВИДЕО СТРАНИЦА');
// Используем утилиту для повторных попыток
core.retryWithBackoff(() => core.VideoWindow.addButtonToVideoWindow());
const videoObserver = new MutationObserver(() => {
core.VideoWindow.addButtonToVideoWindow();
});
videoObserver.observe(document.body, {
childList: true,
subtree: true
});
}
// Главная страница
if (core.Mnemoschema) {
debugLog('🏠 ГЛАВНАЯ СТРАНИЦА');
const addMnemoButton = () => {
if (!core.activeSchemeButton) {
core.Mnemoschema.addSchemeButton();
}
};
// Используем утилиту для повторных попыток
core.retryWithBackoff(addMnemoButton);
}
debugLog('========== ГОТОВО ==========');
}
// Обработка запроса на однократный вход из popup
if (typeof chrome !== 'undefined' && chrome.runtime && chrome.runtime.onMessage) {
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'PERFORM_LOGIN') {
const core = window.VideoIPRedirect;
if (!core || !core.AutoLogin) {
sendResponse({ ok: false, error: 'not_ready' });
return true;
}
const result = core.AutoLogin.performLoginOnce();
sendResponse(result);
return true;
}
});
}
})();