MediaWiki:Common.js: Difference between revisions

From Church of God Knowledge Encyclopedia
Jump to navigation Jump to search
No edit summary
No edit summary
 
(98 intermediate revisions by the same user not shown)
Line 1: Line 1:
/* 이 자바스크립트 설정은 모든 문서, 모든 사용자에게 적용됩니다. */
//Naver Analytics
var NaverCdn = document.createElement('script');
NaverCdn.src = '//wcs.naver.net/wcslog.js';
document.body.appendChild(NaverCdn);
if (!wcs_add) var wcs_add = {};
wcs_add['wa'] = 'ab0e0ecee3c040';


//Google Analytics
/* GA4: single ID + language tagging (MediaWiki 1.42.3) */
var GoogleCdn = document.createElement('script');
(function () {
GoogleCdn.src = 'https://www.googletagmanager.com/gtag/js?id=G-LTWMMR6YSB';
// 중복 로드 방지
document.body.appendChild(GoogleCdn);
if (window.__GA4_LOADED__) return;
window.dataLayer = window.dataLayer || [];
window.__GA4_LOADED__ = true;
function gtag() {
    dataLayer.push(arguments);
var GA_ID = 'G-YGT3D2Q9QW';  
}
gtag('js', new Date());
gtag('config', 'G-LTWMMR6YSB');


/* TOP 버튼 */
// 언어 결정: 가장 신뢰도 높은 wgContentLanguage, 없으면 경로 프리픽스로 보완
var topButton = document.createElement('div');
var pathLang = (location.pathname.split('/')[1] || '').toLowerCase();  
topButton.id = 'top-button';
var lang = (mw.config && mw.config.get('wgContentLanguage'))  
 
        || (['en','es','ko','vi','pt','ne'].includes(pathLang) ? pathLang : 'ko');
document.body.appendChild(topButton);
// <head>에 gtag 로더 삽입
window.addEventListener('scroll', function (e) {
var s = document.createElement('script');
    if (window.scrollY > 300) {
s.async = true;
        topButton.classList.add('active');
s.src = 'https://www.googletagmanager.com/gtag/js?id=' + encodeURIComponent(GA_ID);
    } else {
document.head.appendChild(s);
        topButton.classList.remove('active');
    }
window.dataLayer = window.dataLayer || [];
});
function gtag(){ dataLayer.push(arguments); }
topButton.addEventListener('click', function (e) {
window.gtag = gtag;
    try {
        window.scrollTo({
gtag('js', new Date());
            top: 0,
            left: 0,
// 🔹 자동 page_view 끄기
            behavior: 'smooth',
gtag('config', GA_ID, {
        });
send_page_view: false,
    } catch (e) {
debug_mode: true
        window.scrollTo(0, 0);
});
    }
});
     // 사용자 속성
/* 대문 섹션 토글 */
     gtag('set', 'user_properties', {
if (mw.config.get('wgPageName') == '대문' || mw.config.get('wgPageName') == '대문테스트') {
         site_language: lang,
    var titles = document.querySelectorAll('.cog-box-title');
         browser_language: navigator.language || navigator.userLanguage
    for (var i = 0; i < titles.length; i++) {
        titles[i].addEventListener('click', function (e) {
            if (e.currentTarget.classList.contains('open')) {
                e.currentTarget.classList.remove('open');
            } else {
                e.currentTarget.classList.add('open');
            }
        });
    }
}
 
/*모든 문서 */
if (mw.config.get('wgPageName').toLowerCase() == 'list_of_all_documents') {
    var list = document.querySelectorAll('.mw-allpages-body li');
    for (var i = 0; i < list.length; i++) {
        var title = list[i].querySelector('a').title;
        if (title.indexOf(':') != -1) {
            list[i].parentNode.removeChild(list[i]);
        }
    }
    document.querySelector('.cog-commonpages').style.display = '';
}
var mouseX=0;
var mouseY=0;
/* 각주 팝업창 위치 보정 DOM */
document.body.addEventListener(
    'DOMNodeInserted',
    function (e) {
        if (e.target.classList && e.target.classList.contains('rt-tooltip')) {
            requestAnimationFrame(function () {
            var linkId = e.target.id.substring(3);
            var $link = document.querySelector('#'+linkId);
            var linkTop = $link.getBoundingClientRect().top + window.scrollY;
           
                var bodyTop = document.body.getBoundingClientRect().top + window.scrollY;
                var top = parseInt(window.getComputedStyle(e.target).top);
               
                var bodyLeft = document.body.getBoundingClientRect().left;
                var left = parseInt(window.getComputedStyle(e.target).left);
               
                console.log(top , bodyTop , window.scrollY);
                e.target.style.left = left - bodyLeft + 'px';
                e.target.style.top = linkTop - bodyTop - e.target.offsetHeight + 'px';
                console.log(e.target);
               
            });
        }
    },
    false
);
 
 
/* 우클릭 방지  */
window.oncontextmenu = function (e) {
    return e.preventDefault();
};
window.onselectstart = function (e) {
    return e.preventDefault();
};
 
/* 존재하지 않는 문서 페이지의 '기록' 링크 삭제 */
if (mw.config.get('wgUserId') == null && document.querySelector('.plainlinks a')) {
    document.querySelector('.plainlinks a').removeAttribute('href');
    document.querySelector('.plainlinks a').classList.add('disable');
}
 
// 대문 공유 버튼
var sharebox = document.querySelector('.wikishare_toolbox');
if (sharebox) {
    sharebox.classList.add('a2a_kit_size_20');
    sharebox.classList.add('a2a_kit');
    var shares = ['Facebook', 'Twitter', 'Email', 'Line', 'Kakao', 'SMS'];
    for (var i in shares) {
        var elem = document.querySelector('[title="Share on ' + shares[i] + '"] a');
        elem.href = '';
        elem.classList.add('a2a_button_' + shares[i].toLowerCase());
    }
    document.querySelector('[title="Share on KakaoTalk"] a').href = '#';
    document.querySelector('[title="Share on KakaoTalk"] a').removeAttribute('target');
 
    var share_cdn = document.createElement('script');
    share_cdn.src = 'https://static.addtoany.com/menu/page.js';
    var kakao_cdn = document.createElement('script');
    kakao_cdn.src = 'https://developers.kakao.com/sdk/js/kakao.min.js';
    document.body.appendChild(share_cdn);
    document.body.appendChild(kakao_cdn);
 
    // 페이지 로딩 이후 초기화해야할 내용 정의
    initScript();
    function initScript() {
        var retry = false;
 
        // 카카오 링크 초기화
        if (window.initKakaoLink != true) {
            var $kakao = document.querySelector('[title="Share on KakaoTalk"]');
            if (window.Kakao && $kakao) {
                // 사용할 앱의 JavaScript 키를 설정해 주세요.
                Kakao.init('214de4d25d41a7b837b7bbeb75631c90');
                $kakao.children[0].style.display = 'inline';
                $kakao.onclick = sendScrap; // 카카오 Link 공유 API 사용
                window.initKakaoLink = true;
            } else retry = true;
        }
 
        // 링크 복사 초기화
        if (window.initCopyLink != true) {
            var $copy = document.querySelector('.wikishare_button_Copy');
            if ($copy) {
                $copy.style.display = 'inline';
                $copy.addEventListener('click', function (e) {
                    copyStringToClipboard(decodeURI(location.href));
                    alert('Saved the link to the clipboard.');
                    e.preventDefault();
                });
                window.initCopyLink = true;
            } else retry = true;
        }
 
        // 애널리틱스
        if (window.initWcs != true) {
            if (window.wcs) {
                wcs_do();
                window.initWcs = true;
            } else retry = true;
        }
 
        if (retry) setTimeout(initScript, 300);
     }
}
 
// 문자열을 클립보드에 저장
function copyStringToClipboard(str) {
     var el = document.createElement('textarea');
    el.value = str;
    el.setAttribute('readonly', '');
    el.style = { position: 'absolute', left: '-9999px' };
    document.body.appendChild(el);
    el.select();
    document.execCommand('copy');
    document.body.removeChild(el);
}
 
function sendScrap() {
    // 카카오 Link 공유 API 사용
    Kakao.Link.sendScrap({
         requestUrl: location.href,
         templateId: 91817,
        templateArgs: {
            TITLE: og('title', 'Church of God Knowledge Encyclopedia'),
            DESC: og('description'),
            THUMB: thumb(),
            PAGE: path(),
        },
     });
     });
    function og(name, defaultVal) {
gtag('event', 'page_view', {
        var $meta = document.querySelector('meta[property="og:' + name + '"]');
    page_location: location.href,
        if ($meta) return $meta.getAttribute('content');
    page_path: location.pathname + location.search,
        else return defaultVal ? defaultVal : '';
    page_title: document.title,
    }
    content_group: lang
    function thumb() {
});
        var img = og('image');
})();
        if (!img) {
            var $img = document.querySelector('img[src]');
            if ($img) {
                img = $img.src;
            }
        }
        if (img.indexOf('http') != 0) img = location.origin + (img[0] == '/' ? img : '/' + img);
        return img;
    }
    function path() {
        if (location.pathname[0] == '/') return location.pathname.substring(1) + location.search;
        else return location.pathname + location.search;
    }
}
 
// 앨범 레이아웃 보정
updateAllAlbum();
window.addEventListener('load', updateAllAlbum);
window.addEventListener('resize', updateAllAlbum);
function updateAllAlbum() {
    var $albums = document.querySelectorAll('.custom-album');
    for (var i = 0; i < $albums.length; i++) {
        updateAlbum($albums[i]);
    }
}
function updateAlbum($elem) {
    var lineMax = 3;
    for (var i = 0; i < $elem.classList.length; i++) {
        if ($elem.classList[i].indexOf('line-max-') == 0) {
            lineMax = Number($elem.classList[i].replace('line-max-', ''));
        }
    }
 
    var totalWidth = $elem.clientWidth;
 
    if ($elem.children.length > 0) {
        for (var i = $elem.children.length - 1; i >= 0; i--) {
            if (!$elem.children[i].classList.contains('albumitem')) {
                $elem.children[i].remove();
                continue;
            }
            $elem.children[i].style.width = '';
            $elem.children[i].style.height = '';
        }
 
        if (window.innerWidth < 720) return;
 
        var lineTotalRatio = [];
        for (var i = 0; i < $elem.children.length; i++) {
            var lineIdx = Math.floor(i / lineMax);
            var $img = $elem.children[i].querySelector('img');
 
            if (!$img || $img.naturalWidth == 0) continue;
 
            if (lineTotalRatio[lineIdx] == undefined) {
                lineTotalRatio[lineIdx] = 0;
            }
 
            lineTotalRatio[lineIdx] += $img.naturalWidth / $img.naturalHeight;
        }
 
        for (var i = 0; i < $elem.children.length; i++) {
            var totalRatio = lineTotalRatio[Math.floor(i / lineMax)];
            var $img = $elem.children[i].querySelector('img');
 
            if (!$img || $img.naturalWidth == 0) continue;
 
            var ratio = $img.naturalWidth / $img.naturalHeight;
            var width = (ratio / totalRatio) * (totalWidth - 6 * lineMax) + 6;
            $elem.children[i].style.width = (width / totalWidth) * 100 + '%';
        }
    }
}
//const bodyElem = document.querySelector('#bodyContent');
//bodyElem.classList.add("mw-body-content");


//const navigationElem = document.querySelector('.minerva-user-navigation');
mw.loader.load('/resources/assets/common/common.js');
//navigationElem.remove()

Latest revision as of 10:25, 23 March 2026

//Naver Analytics
var NaverCdn = document.createElement('script');
NaverCdn.src = '//wcs.naver.net/wcslog.js';
document.body.appendChild(NaverCdn);
if (!wcs_add) var wcs_add = {};
wcs_add['wa'] = 'ab0e0ecee3c040';

/* GA4: single ID + language tagging (MediaWiki 1.42.3) */
(function () {
	// 중복 로드 방지
	if (window.__GA4_LOADED__) return;
	window.__GA4_LOADED__ = true;
	
	var GA_ID = 'G-YGT3D2Q9QW'; 

	// 언어 결정: 가장 신뢰도 높은 wgContentLanguage, 없으면 경로 프리픽스로 보완
	var pathLang = (location.pathname.split('/')[1] || '').toLowerCase(); 
	var lang = (mw.config && mw.config.get('wgContentLanguage')) 
	         || (['en','es','ko','vi','pt','ne'].includes(pathLang) ? pathLang : 'ko');
	// <head>에 gtag 로더 삽입
	var s = document.createElement('script');
	s.async = true;
	s.src = 'https://www.googletagmanager.com/gtag/js?id=' + encodeURIComponent(GA_ID);
	document.head.appendChild(s);
	
	window.dataLayer = window.dataLayer || [];
	function gtag(){ dataLayer.push(arguments); }
	window.gtag = gtag;
	
	gtag('js', new Date());
	
	// 🔹 자동 page_view 끄기
	gtag('config', GA_ID, {
		send_page_view: false,
		debug_mode: true
	});
	
    // 사용자 속성
    gtag('set', 'user_properties', {
        site_language: lang,
        browser_language: navigator.language || navigator.userLanguage
    });
	gtag('event', 'page_view', {
	    page_location: location.href,
	    page_path: location.pathname + location.search,
	    page_title: document.title,
	    content_group: lang
	});
})();

mw.loader.load('/resources/assets/common/common.js');