instead of pasting the code at page level, past it at site level throuch the settings of your project > custom code > footer as seen on the screen shot bellow. I copied the code at page level so you can see it with the read-only preview link I shared.
By the way, here is a shorter version, without comments:
(function switchLanguage() {
const switchButton = document.getElementById('switchLink');
let protocol = window.location.protocol;
let currentHost = window.location.host;
let pathNameArray = window.location.pathname.split('/');
switchButton.addEventListener('click', function() {
if (pathNameArray[1] == 'fr') {
window.open(protocol + '//' + currentHost + '/en/' + pathNameArray[2], '_self');
} else if (pathNameArray[1] == 'en') {
window.open(protocol + '//' + currentHost + '/fr/' + pathNameArray[2], '_self');
}
}
);
})();
Hope that helps !