saferedirect.js
Version:
Dış bağlantıları tespit edip yönlendirme sayfasına gönderen bir kütüphane
50 lines (43 loc) • 1.7 kB
JavaScript
class RedirectHandler {
constructor(options = {}) {
this.redirectPage = options.redirectPage || '/redirect.html'; // Varsayılan yönlendirme sayfası
this.timeout = options.timeout || 5000; // Opsiyonel zamanlayıcı (ms cinsinden)
this.currentDomain = window.location.hostname; // Mevcut domain
this.init();
}
// Sayfadaki tüm <a> etiketlerini tara
init() {
const links = document.getElementsByTagName('a');
for (let link of links) {
if (this.isExternalLink(link)) {
this.addRedirectListener(link);
}
}
}
// Linkin dış bağlantı olup olmadığını kontrol et
isExternalLink(link) {
const href = link.getAttribute('href');
if (!href) return false;
// Eğer href mevcut domain ile başlamıyorsa dış bağlantıdır
try {
const url = new URL(href, window.location.origin);
return url.hostname !== this.currentDomain;
} catch (e) {
return false; // Geçersiz URL'ler için false döndür
}
}
// Event listener ekle
addRedirectListener(link) {
link.addEventListener('click', (event) => {
event.preventDefault(); // Varsayılan yönlendirmeyi engelle
const targetUrl = link.getAttribute('href');
const redirectUrl = `${this.redirectPage}?url=${encodeURIComponent(targetUrl)}`;
window.location.href = redirectUrl; // Yönlendirme sayfasına git
});
}
}
// Kütüphaneyi başlatma fonksiyonu
function setupRedirect(options) {
return new RedirectHandler(options);
}
export default setupRedirect;