Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 });
Expand All @@ -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) {
Expand Down