How to open external links in the same new tab in the same browser window ?
( i.e. first click in an external link triggers a new tab, but subsequent clicks on the external links open up in that same tab without creating additional tabs in the browser window )
Example : See how LegWorkStudio doing it in their portfolio in between the following links
Opening external links in the same new tab can be a bit tricky due to browser security policies, but it's possible with JavaScript only when the external linked files are in the same server (Remote or localhost).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>External Links</title>
</head>
<body>
<a href="./link1.html" class="external-link">External Link 1</a>
<a href="./link2.html" class="external-link">External Link 2</a>
<script>
document.addEventListener('DOMContentLoaded', (event) => {
let externalTab;
document.querySelectorAll('a.external-link').forEach(link => {
link.addEventListener('click', function(event) {
event.preventDefault();
const url = this.href;
if (!externalTab || externalTab.closed) {
externalTab = window.open(url, '_blank');
} else {
externalTab.location.href = url;
}
externalTab.focus();
});
});
});
</script>
</body>
</html>
The above example contains two external links with the class external-link. Below are the step-by-step solution used:
This ensures that the first click opens a new tab, and subsequent clicks reuse that same tab for external links.