I was searching for a few hours and came across this link. It works only for href from what I can see - I did try buttons, but that didn't work.
index.html
<a href="page.html#home">Home</a> | <a href="page.html#profile">Profile</a> | <a href="page.html#contact">Contact</a> |
page.html
<ul class="nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item" role="presentation">
<a class="nav-link active" id="home-tab" data-bs-toggle="tab" data-bs-target="#home" href="#home" role="tab" aria-controls="home" aria-selected="true">Home</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="profile-tab" data-bs-toggle="tab" data-bs-target="#profile" href="#profile" role="tab" aria-controls="profile" aria-selected="false">Profile</a>
</li>
<li class="nav-item" role="presentation">
<a class="nav-link" id="contact-tab" data-bs-toggle="tab" data-bs-target="#contact" href="#contact" role="tab" aria-controls="contact" aria-selected="false">Contact</a>
</li>
</ul>
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">home</div>
<div class="tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab">profile</div>
<div class="tab-pane fade" id="contact" role="tabpanel" aria-labelledby="contact-tab">contact</div>
</div>
Javascript (vanilla)
// deep linking - load tab on refresh
let url = location.href.replace(/\/$/, '');
if (location.hash) {
const hash = url.split('#');
const currentTab = document.querySelector('#myTab a[href="#' + hash[1] + '"]');
const curTab = new bootstrap.Tab(currentTab);
curTab.show();
url = location.href.replace(/\/#/, '#');
history.replaceState(null, null, url);
setTimeout(() => {
window.scrollTop = 0;
}, 400);
}
// change url based on selected tab
const selectableTabList = [].slice.call(document.querySelectorAll('a[data-bs-toggle="tab"]'));
selectableTabList.forEach((selectableTab) => {
const selTab = new bootstrap.Tab(selectableTab);
selectableTab.addEventListener('click', function () {
var newUrl;
const hash = selectableTab.getAttribute('href');
if (hash == '#home-tab') {
newUrl = url.split('#')[0];
} else {
newUrl = url.split('#')[0] + hash;
}
history.replaceState(null, null, newUrl);
});
});
In my case I didn't want all my UL using the same ID. So I changed it to class instead in the JS and added the class to my ul.
JS
const currentTab = document.querySelector('.deepLink a[href="#' + hash[1] + '"]');
html
<ul class="nav nav-pills nav-fill deepLink" role="tablist">
And the award goes to Viper
https://www.viperswebdesign.com/blog/how-to-add-deep-linking-to-the-bootstrap-5-tabs-component