Skip to content

Make external links open in new tabs while preserving internal link behavior #15080

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
57 changes: 57 additions & 0 deletions theme/src/ts/external-links.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/**
* Adds target="_blank" to all external links to make them open in a new tab.
* Internal links (links to the same domain) remain unchanged.
*/

(function() {
// Function to process all links on the page
function processExternalLinks() {
// Get the current domain (without protocol, www, or trailing slash)
const currentDomain = window.location.hostname.replace(/^www\./, '');

// Select all links in the document
const links = document.querySelectorAll('a[href]');

// Process each link
links.forEach(link => {
const href = link.getAttribute('href');

// Skip links without href, anchor links, or javascript: links
if (!href || href.startsWith('#') || href.startsWith('javascript:')) {
return;
}

try {
// Try to parse the URL (this will throw for relative URLs)
const url = new URL(href, window.location.origin);
const linkDomain = url.hostname.replace(/^www\./, '');

// If the domain is different from the current domain, it's external
if (linkDomain !== currentDomain) {
// Add target="_blank" and rel="noopener" (for security)
link.setAttribute('target', '_blank');

// Add rel="noopener noreferrer" for security
const relAttr = link.getAttribute('rel') || '';
if (!relAttr.includes('noopener')) {
const newRel = relAttr ? `${relAttr} noopener` : 'noopener';
link.setAttribute('rel', newRel);
}
}
} catch (e) {
// If URL parsing fails, it's likely a relative URL (internal link)
return;
}
});
}

// Execute when DOM is fully loaded
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', processExternalLinks);
} else {
processExternalLinks();
}

// Also process links after any potential dynamic content updates
window.addEventListener('load', processExternalLinks);
})();
1 change: 1 addition & 0 deletions theme/src/ts/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import "./docs-main";
import "./redirects";
import "./algolia/autocomplete";
import "./terraform-compare";
import "./external-links";

// Register all Stencil components.
defineCustomElements();
Loading