feature: Add script to tag external links to open in new tab and add class for styling

This commit is contained in:
Keith Solomon
2025-11-11 11:30:48 -06:00
parent 06f714f7c3
commit aae6608153
2 changed files with 56 additions and 13 deletions

View File

@@ -0,0 +1,39 @@
/**
* Tags external links in the document with appropriate attributes and styling.
*
* This function identifies all anchor elements with href attributes and determines
* if they point to external domains. External links are enhanced with:
* - Accessibility label indicating they open in a new tab
* - target="_blank" to open in new tab
* - rel="noopener noreferrer" for security
* - Custom CSS class "extLink" for styling
*
* Links are considered external if their host differs from the current page's host.
* Malformed URLs are silently ignored.
*
* @function tagExternalLinks
* @returns {void}
*/
function tagExternalLinks() {
const currentHost = window.location.host;
document.querySelectorAll('a[href]').forEach(link => {
try {
const url = new URL(link.href, window.location.href);
// If the link's host is different from the current host, treat as external
if (url.host !== currentHost) {
link.setAttribute('aria-label', 'External link, opens in a new tab');
link.setAttribute('target', '_blank');
link.setAttribute('rel', 'noopener noreferrer'); // Security best practice
link.classList.add('extLink'); // Add a custom class for icons or other styling
}
} catch (e) {
// Ignore malformed URLs
}
});
}
export default tagExternalLinks;

View File

@@ -5,6 +5,7 @@
import { registerButtonComponent } from './components/button.js'; import { registerButtonComponent } from './components/button.js';
import { registerBackToTopButton } from './components/backToTop.js'; import { registerBackToTopButton } from './components/backToTop.js';
import GetHeaderHeight from './modules/GetHeaderHeight.js'; import GetHeaderHeight from './modules/GetHeaderHeight.js';
import tagExternalLinks from './modules/TagExternalLinks.js';
import Navigation from './modules/Navigation.js'; import Navigation from './modules/Navigation.js';
// Add passive event listeners // Add passive event listeners
@@ -50,6 +51,9 @@ import Navigation from './modules/Navigation.js';
* Application entrypoint * Application entrypoint
*/ */
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
// Tag external links
tagExternalLinks();
// Register button component // Register button component
registerButtonComponent(); registerButtonComponent();
registerBackToTopButton(); registerBackToTopButton();