Files
CHOMPStation2/tgui/packages/tgui_ch/links.js
2023-05-23 17:43:01 +02:00

47 lines
1.1 KiB
JavaScript

/**
* @file
* @copyright 2020 Aleksej Komarov
* @license MIT
*/
/**
* Prevents baby jailing the user when he clicks an external link.
*/
export const captureExternalLinks = () => {
// Subscribe to all document clicks
document.addEventListener('click', (e) => {
/** @type {HTMLElement} */
let target = e.target;
// Recurse down the tree to find a valid link
while (true) {
// Reached the end, bail.
if (!target || target === document.body) {
return;
}
const tagName = String(target.tagName).toLowerCase();
if (tagName === 'a') {
break;
}
target = target.parentElement;
}
const hrefAttr = target.getAttribute('href') || '';
// Leave BYOND links alone
const isByondLink = hrefAttr.charAt(0) === '?' || hrefAttr.startsWith('byond://');
if (isByondLink) {
return;
}
// Prevent default action
e.preventDefault();
// Normalize the URL
let url = hrefAttr;
if (url.toLowerCase().startsWith('www')) {
url = 'https://' + url;
}
// Open the link
Byond.sendMessage({
type: 'openLink',
url,
});
});
};