diff --git a/taccsite_cms/static/site_cms/js/modules/setTargetForExternalLinks.js b/taccsite_cms/static/site_cms/js/modules/setTargetForExternalLinks.js index b35b86ce3..d88cfbf24 100644 --- a/taccsite_cms/static/site_cms/js/modules/setTargetForExternalLinks.js +++ b/taccsite_cms/static/site_cms/js/modules/setTargetForExternalLinks.js @@ -4,6 +4,29 @@ */ export const DEFAULT_LINKS = document.querySelectorAll('body > :is(header, main, footer) a'); +/** + * Check if two hosts are effectively the same domain + * @param {string} linkHost - The host from the link + * @param {string} baseHost - The current page's host + * @param {string[]} subdomains - List of valid subdomains + * @returns {boolean} + */ +function isSameDomain(linkHost, baseHost, subdomains) { + // Direct match + if (linkHost === baseHost) return true; + + // Link is to subdomain of base host + if (subdomains.some(subdomain => linkHost === `${subdomain}.${baseHost}`)) return true; + + // Link is to root domain while we're on subdomain + if (subdomains.some(subdomain => + baseHost.startsWith(`${subdomain}.`) && + linkHost === baseHost.replace(`${subdomain}.`, '') + )) return true; + + return false; +} + /** * Make links with absolute URLs open in new tab, and: * - add accessible markup @@ -18,7 +41,10 @@ export default function findLinksAndSetTargets( links = DEFAULT_LINKS, opts = { shouldFilter: true, }) { const baseDocHost = document.location.host; - const baseDocHostWithSubdomain= `www.${ baseDocHost }`; + const standardSubdomains = ['www', 'pprd', 'prod', 'dev']; + const similarHosts = standardSubdomains.map( + subdomain => `${subdomain}.${baseDocHost}` + ); if ( opts.shouldDebug ) { console.log({ links, opts }); @@ -33,7 +59,7 @@ export default function findLinksAndSetTargets( links = DEFAULT_LINKS, opts = { const isMailto = ( linkHref.indexOf('mailto:') === 0 ); const isAbsolute = ( linkHref.indexOf('http') === 0 ); - const isSameHost = ( link.host === baseDocHost || link.host === baseDocHostWithSubdomain ); + const isSameHost = isSameDomain(link.host, baseDocHost, standardSubdomains); const shouldOpenInNewTab = ( ! isSameHost || isMailto ); if (opts.shouldDebug) {