Если на вашем сайте пользователи или вы сами часто делитесь ссылками на сторонние ресурсы, то вы наверняка задумывались о безопасности. Уход пользователя на неизвестный сайт — это всегда риск: там может оказаться фишинг, спам или вредоносное ПО. К тому же, поисковые системы любят, когда веб-мастера заботятся о своей аудитории.
Сегодня мы разберем отличный скрипт, который перехватывает клики по всем внешним ссылкам и выводит стильное модальное окно предупреждения.
🌟 В чем фишка этого скрипта?
Абсолютно чистый JavaScript (Vanilla JS): Скрипт написан без использования сторонних библиотек. Ему не нужен jQuery — он будет работать на абсолютно любом сайте и движке (включая uCoz).
Белый список доменов (White List): Вы можете указать свой домен, и переходы по внутренним страницам (или дружественным сайтам) будут происходить мгновенно и без лишних окон.
Полная автономность: Скрипт сам генерирует HTML-разметку и CSS-стили прямо «на лету». Вам не нужно отдельно копаться в таблице стилей сайта.
Удобный интерфейс: Окно четко выводит адрес ссылки, на которую кликнул человек, предупреждает о снятии ответственности и предлагает два понятных действия: вернуться назад или продолжить переход в новой вкладке.
🚀 Инструкция по установке
Вам понадобится скопировать код ниже и вставить его в общий шаблон сайта (например, в «Нижняя часть сайта» в uCoz или прямо перед закрывающим тегом </body>).
Код
<script type="text/javascript">
(function () {
let targetUrl = '';
// --- НАСТРОЙКИ ---
// Укажите ваш домен ниже. Ссылки на него НЕ будут вызывать предупреждение!
const allowedDomain = 'htmlstart.ucoz.net';
// -----------------
// Создание модального окна предупреждения
function createModal() {
if (document.getElementById('ext-link-overlay')) return;
// Оверлей (затемнение фона)
const overlay = document.createElement('div');
overlay.id = 'ext-link-overlay';
overlay.style.cssText = `
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 999999;
font-family: 'Segoe UI', Arial, sans-serif;
`;
// Модальное окно
const modal = document.createElement('div');
modal.style.cssText = `
width: 440px;
background: #fff;
border-radius: 12px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
overflow: hidden;
animation: fadeIn_ext 0.3s ease;
`;
// Стили для анимации появления окна
const styleSheet = document.createElement("style");
styleSheet.innerText = `@keyframes fadeIn_ext { from { opacity: 0; transform: scale(0.95); } to { opacity: 1; transform: scale(1); } }`;
document.head.appendChild(styleSheet);
// Заголовок
const header = document.createElement('div');
header.style.cssText = `
padding: 18px;
background: #1a1a1a;
color: #fff;
font-weight: bold;
font-size: 16px;
display: flex;
justify-content: space-between;
align-items: center;
`;
header.textContent = '⚠ Предупреждение: внешняя ссылка';
// Кнопка закрытия (крестик)
const closeBtn = document.createElement('button');
closeBtn.textContent = 'Закрыть';
closeBtn.style.cssText = `
background: #e53935;
color: #fff;
border: none;
padding: 6px 12px;
border-radius: 6px;
cursor: pointer;
font-size: 13px;
transition: background 0.2s;
`;
closeBtn.onmouseenter = () => closeBtn.style.background = '#d32f2f';
closeBtn.onmouseleave = () => closeBtn.style.background = '#e53935';
closeBtn.onclick = closeModal;
header.appendChild(closeBtn);
// Тело модального окна
const body = document.createElement('div');
body.style.cssText = 'padding: 20px; font-size: 14px; color: #333; line-height: 1.5;';
// Функция для создания стильных информационных блоков
function dashedBlock(html) {
const wrap = document.createElement('div');
wrap.style.marginBottom = '14px';
const span = document.createElement('span');
span.style.display = 'block';
span.style.borderBottom = '1px dashed #ccc';
span.style.paddingBottom = '8px';
span.innerHTML = html;
wrap.appendChild(span);
return wrap;
}
body.appendChild(dashedBlock(
'Вы собираетесь перейти по внешней ссылке:<br><b id="ext-link-url" style="color: #2563eb; word-break: break-all;"></b>'
));
body.appendChild(dashedBlock(
'Администрация сайта не несёт ответственности за содержание сторонних ресурсов.'
));
body.appendChild(dashedBlock(
'Ссылка откроется в безопасном режиме в новом окне.'
));
// Нижний колонтитул с кнопками управления
const footer = document.createElement('div');
footer.style.cssText = `
padding: 16px 20px;
text-align: right;
background: #f8f9fa;
border-top: 1px solid #eee;
`;
const cancelBtn = document.createElement('button');
cancelBtn.innerHTML = '⛔ Отменить';
cancelBtn.style.cssText = `
background: #64748b;
color: #fff;
border: none;
padding: 10px 18px;
border-radius: 6px;
cursor: pointer;
font-size: 14px;
margin-right: 12px;
transition: background 0.2s;
`;
cancelBtn.onmouseenter = () => cancelBtn.style.background = '#475569';
cancelBtn.onmouseleave = () => cancelBtn.style.background = '#64748b';
cancelBtn.onclick = closeModal;
const goBtn = document.createElement('button');
goBtn.innerHTML = '➡️ Перейти';
goBtn.style.cssText = `
background: #2563eb;
color: #fff;
border: none;
padding: 10px 18px;
border-radius: 6px;
cursor: pointer;
font-size: 14px;
font-weight: bold;
transition: background 0.2s;
`;
goBtn.onmouseenter = () => goBtn.style.background = '#1d4ed8';
goBtn.onmouseleave = () => goBtn.style.background = '#2563eb';
goBtn.onclick = goToLink;
footer.append(cancelBtn, goBtn);
modal.append(header, body, footer);
overlay.appendChild(modal);
document.body.appendChild(overlay);
}
// Закрытие модального окна
function closeModal() {
const overlay = document.getElementById('ext-link-overlay');
if (overlay) overlay.remove();
}
// Переход по внешней ссылке
function goToLink() {
window.open(targetUrl, '_blank');
closeModal();
}
// Глобальная функция для вызова предупреждения
window.externalLinkWarning = function (url) {
targetUrl = url;
createModal();
document.getElementById('ext-link-url').textContent = url;
};
// Перехват кликов по всем ссылкам на странице
document.addEventListener('click', function (e) {
const link = e.target.closest('a[href]');
if (!link) return;
const href = link.getAttribute('href');
if (!href) return;
// Игнорируем javascript-ссылки и пустые якоря
if (href.trim().toLowerCase().startsWith('javascript') || href.startsWith('#')) return;
try {
const url = new URL(link.href, window.location.origin);
// Проверяем, относится ли ссылка к разрешённому домену
if (
url.hostname === allowedDomain ||
url.hostname.endsWith('.' + allowedDomain)
) {
return; // Своя ссылка — пропускаем без предупреждения
}
} catch {
return; // Ошибка обработки URL — не трогаем ссылку
}
// Если ссылка внешняя — блокируем стандартный переход и вызываем наше окно
e.preventDefault();
externalLinkWarning(link.href);
});
})();
</script>
(function () {
let targetUrl = '';
// --- НАСТРОЙКИ ---
// Укажите ваш домен ниже. Ссылки на него НЕ будут вызывать предупреждение!
const allowedDomain = 'htmlstart.ucoz.net';
// -----------------
// Создание модального окна предупреждения
function createModal() {
if (document.getElementById('ext-link-overlay')) return;
// Оверлей (затемнение фона)
const overlay = document.createElement('div');
overlay.id = 'ext-link-overlay';
overlay.style.cssText = `
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 999999;
font-family: 'Segoe UI', Arial, sans-serif;
`;
// Модальное окно
const modal = document.createElement('div');
modal.style.cssText = `
width: 440px;
background: #fff;
border-radius: 12px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
overflow: hidden;
animation: fadeIn_ext 0.3s ease;
`;
// Стили для анимации появления окна
const styleSheet = document.createElement("style");
styleSheet.innerText = `@keyframes fadeIn_ext { from { opacity: 0; transform: scale(0.95); } to { opacity: 1; transform: scale(1); } }`;
document.head.appendChild(styleSheet);
// Заголовок
const header = document.createElement('div');
header.style.cssText = `
padding: 18px;
background: #1a1a1a;
color: #fff;
font-weight: bold;
font-size: 16px;
display: flex;
justify-content: space-between;
align-items: center;
`;
header.textContent = '⚠ Предупреждение: внешняя ссылка';
// Кнопка закрытия (крестик)
const closeBtn = document.createElement('button');
closeBtn.textContent = 'Закрыть';
closeBtn.style.cssText = `
background: #e53935;
color: #fff;
border: none;
padding: 6px 12px;
border-radius: 6px;
cursor: pointer;
font-size: 13px;
transition: background 0.2s;
`;
closeBtn.onmouseenter = () => closeBtn.style.background = '#d32f2f';
closeBtn.onmouseleave = () => closeBtn.style.background = '#e53935';
closeBtn.onclick = closeModal;
header.appendChild(closeBtn);
// Тело модального окна
const body = document.createElement('div');
body.style.cssText = 'padding: 20px; font-size: 14px; color: #333; line-height: 1.5;';
// Функция для создания стильных информационных блоков
function dashedBlock(html) {
const wrap = document.createElement('div');
wrap.style.marginBottom = '14px';
const span = document.createElement('span');
span.style.display = 'block';
span.style.borderBottom = '1px dashed #ccc';
span.style.paddingBottom = '8px';
span.innerHTML = html;
wrap.appendChild(span);
return wrap;
}
body.appendChild(dashedBlock(
'Вы собираетесь перейти по внешней ссылке:<br><b id="ext-link-url" style="color: #2563eb; word-break: break-all;"></b>'
));
body.appendChild(dashedBlock(
'Администрация сайта не несёт ответственности за содержание сторонних ресурсов.'
));
body.appendChild(dashedBlock(
'Ссылка откроется в безопасном режиме в новом окне.'
));
// Нижний колонтитул с кнопками управления
const footer = document.createElement('div');
footer.style.cssText = `
padding: 16px 20px;
text-align: right;
background: #f8f9fa;
border-top: 1px solid #eee;
`;
const cancelBtn = document.createElement('button');
cancelBtn.innerHTML = '⛔ Отменить';
cancelBtn.style.cssText = `
background: #64748b;
color: #fff;
border: none;
padding: 10px 18px;
border-radius: 6px;
cursor: pointer;
font-size: 14px;
margin-right: 12px;
transition: background 0.2s;
`;
cancelBtn.onmouseenter = () => cancelBtn.style.background = '#475569';
cancelBtn.onmouseleave = () => cancelBtn.style.background = '#64748b';
cancelBtn.onclick = closeModal;
const goBtn = document.createElement('button');
goBtn.innerHTML = '➡️ Перейти';
goBtn.style.cssText = `
background: #2563eb;
color: #fff;
border: none;
padding: 10px 18px;
border-radius: 6px;
cursor: pointer;
font-size: 14px;
font-weight: bold;
transition: background 0.2s;
`;
goBtn.onmouseenter = () => goBtn.style.background = '#1d4ed8';
goBtn.onmouseleave = () => goBtn.style.background = '#2563eb';
goBtn.onclick = goToLink;
footer.append(cancelBtn, goBtn);
modal.append(header, body, footer);
overlay.appendChild(modal);
document.body.appendChild(overlay);
}
// Закрытие модального окна
function closeModal() {
const overlay = document.getElementById('ext-link-overlay');
if (overlay) overlay.remove();
}
// Переход по внешней ссылке
function goToLink() {
window.open(targetUrl, '_blank');
closeModal();
}
// Глобальная функция для вызова предупреждения
window.externalLinkWarning = function (url) {
targetUrl = url;
createModal();
document.getElementById('ext-link-url').textContent = url;
};
// Перехват кликов по всем ссылкам на странице
document.addEventListener('click', function (e) {
const link = e.target.closest('a[href]');
if (!link) return;
const href = link.getAttribute('href');
if (!href) return;
// Игнорируем javascript-ссылки и пустые якоря
if (href.trim().toLowerCase().startsWith('javascript') || href.startsWith('#')) return;
try {
const url = new URL(link.href, window.location.origin);
// Проверяем, относится ли ссылка к разрешённому домену
if (
url.hostname === allowedDomain ||
url.hostname.endsWith('.' + allowedDomain)
) {
return; // Своя ссылка — пропускаем без предупреждения
}
} catch {
return; // Ошибка обработки URL — не трогаем ссылку
}
// Если ссылка внешняя — блокируем стандартный переход и вызываем наше окно
e.preventDefault();
externalLinkWarning(link.href);
});
})();
</script>
⚙ Настройка под себя
После того как вставите код, обязательно найдите в самом начале скрипта строку:
const allowedDomain = 'htmlstart.ucoz.net';
Замените htmlstart.ucoz.net на домен своего сайта. Это нужно для того, чтобы скрипт понимал, какие ссылки внутренние (их проверять не надо), а какие ведут на другие ресурсы.
Скрипт полностью готов к интеграции. Забирайте себе в копилку полезных решений и делайте свои сайты безопаснее!