Aquí tienes tu código completo corregido:
const pageCache = {};
const isFirefox = typeof InstallTrigger !== 'undefined';
if (isFirefox) {
// Agrega la clase "firefox" al body
document.body.classList.add('firefox');
// Inserta el SVG para el filtro de desenfoque
const svg = `
<svg style="display: none;">
<filter id="blur-effect">
<feGaussianBlur stdDeviation="10" />
</filter>
</svg>`;
document.body.insertAdjacentHTML('afterbegin', svg);
}
function inicializarScripts() {
[
'inicializarWaveforms',
'inicializarReproductorAudio',
'minimizarform',
'selectorformtipo',
'ajax_submit',
'borrarcomentario',
'colab',
'configuser',
'deletepost',
'diferidopost',
'editarcomentario',
'like',
'notificacioncolab',
'busqueda',
'updateBackgroundColor',
'presentacionmusic',
'seguir',
'registro',
'comentarios',
'botoneditarpost',
'fan',
'perfilpanel',
'smooth',
'navpanel',
'borderborder',
'initializeFormFunctions',
'initializeModalregistro',
'submenu',
'selectortipousuario',
'empezarcolab',
'subidaRolaForm',
'avances',
'updateDates',
'initializeProgressSegments',
'initializeCustomTooltips',
'fondoAcciones',
'pestanasgroup',
'manejoDeLogs',
'progresosinteractive',
'setupScrolling',
'inicializarDescargas',
'handleAllRequests',
'textflux',
'autoFillUserInfo',
'inicializarPestanas',
'meta',
'reporteScript',
'generarGrafico',
'grafico',
'IniciadoresConfigPerfil',
'proyectoForm',
'inicializarAlerta',
'autoRows',
'iniciarRS',
'initializeUI',
'tagsPosts',
'vistaPost',
'initEditWordPress',
'reiniciarCargaDiferida',
'registrarVistas',
'colec',
'cambiarFiltroTiempo',
'filtrosPost',
'contadorDeSamples',
'establecerFiltros',
'actualizarBotonFiltro'
].forEach(function(func) {
if (typeof window[func] === 'function') {
try {
window[func]();
} catch (error) {
console.error('Error al ejecutar ' + func + ':', error);
}
}
});
}
function reinicializar() {
inicializarScripts();
if (window.location.hash && typeof window.mostrarPestana === 'function') {
window.mostrarPestana(window.location.hash);
}
}
window.reinicializar = reinicializar;
// Verificar si ajaxPage está definido antes de acceder a sus propiedades
const login = (typeof ajaxPage !== 'undefined' && ajaxPage.logeado) || false;
function loadStripe(callback) {
if (!login) {
console.log('Login is false, Stripe will not be loaded');
return; // No cargar Stripe si login es false
}
if (typeof Stripe !== 'undefined') return callback();
const script = document.createElement('script');
script.src = 'https://js.stripe.com/v3/';
script.async = true;
script.onload = callback;
document.head.appendChild(script);
}
function initializeStripeFunctions() {
['stripepro', 'stripecompra'].forEach(function(func) {
if (typeof window[func] === 'function') window[func]();
else console.warn(func + ' no está definida');
});
}
function shouldCache(url) {
return !['https://2upra.com/nocache'].some(function(noCacheUrl) {
return new RegExp(noCacheUrl.replace(/\*/g, '.*')).test(url);
});
}
function loadContent(enlace, isPushState) {
console.log('Iniciando carga de contenido:', enlace);
const lowerEnlace = enlace.trim().toLowerCase();
if (!enlace || lowerEnlace.startsWith('javascript:') || lowerEnlace.startsWith('data:') || lowerEnlace.startsWith('vbscript:') || enlace.includes('#') || enlace.includes('descarga_token')) return;
if (pageCache[enlace] && shouldCache(enlace)) {
document.getElementById('content').innerHTML = pageCache[enlace];
if (isPushState) history.pushState(null, '', enlace);
reinicializar();
return;
}
const loadingBar = document.getElementById('loadingBar');
loadingBar.style.cssText = 'width: 70%; opacity: 1; transition: width 0.4s ease';
fetch(enlace)
.then(function(response) { return response.text(); })
.then(function(data) {
const parser = new DOMParser();
const doc = parser.parseFromString(data, 'text/html');
const contentElement = doc.getElementById('content');
if (!contentElement) {
console.error('No se encontró el elemento #content en la respuesta');
return;
}
const content = contentElement.innerHTML;
document.getElementById('content').innerHTML = content;
if (shouldCache(enlace)) pageCache[enlace] = content;
loadingBar.style.cssText = 'width: 100%; transition: width 0.1s ease, opacity 0.3s ease';
setTimeout(function() { loadingBar.style.cssText = 'width: 0%; opacity: 0'; }, 100);
if (isPushState) history.pushState(null, '', enlace);
var scripts = doc.querySelectorAll('script');
scripts.forEach(function(script) {
var newScript = document.createElement('script');
newScript.textContent = script.textContent;
document.body.appendChild(newScript);
});
setTimeout(reinicializar, 100);
})
.catch(function(error) {
console.error('Error al cargar la página:', error);
});
}
document.addEventListener('DOMContentLoaded', function () {
if (!window.location.href.includes('?fb-edit=1')) {
reinicializar();
if (login) {
if (!window.galleInicializado && typeof window.galle === 'function') {
window.galle();
window.galleInicializado = true;
}
if (typeof loadStripe === 'function') {
loadStripe(initializeStripeFunctions);
}
}
}
function handleContentLoad(event, enlace, element) {
// Si el elemento o su padre tiene la clase 'no-ajax', retornar true (omitir AJAX).
if (element.classList.contains('no-ajax') || element.closest('.no-ajax')) return true;
// Asegurarse de que 'enlace' es una cadena válida antes de continuar.
if (typeof enlace !== 'string' || !enlace) {
console.warn('Enlace inválido:', enlace);
return true;
}
// Convertir 'enlace' a minúsculas y eliminar espacios en blanco.
var lowerCaseLink = enlace.trim().toLowerCase();
// Verificar si es un enlace válido que debe manejarse vía AJAX.
if (lowerCaseLink.endsWith('.pdf') || ['https://2upra.com/nocache', 'javascript:', 'data:', 'vbscript:'].some(function(prefix) {
return lowerCaseLink.startsWith(prefix);
}) || enlace.includes('#')) {
return true;
}
// Prevenir el comportamiento por defecto del enlace y cargar el contenido vía AJAX.
event.preventDefault();
loadContent(enlace, true);
return false;
}
document.querySelectorAll('a, button a, .botones-panel').forEach(function(element) {
element.addEventListener('click', function (event) {
var enlace = this.getAttribute('href') || this.getAttribute('data-href') || (this.querySelector('a') && this.querySelector('a').getAttribute('href'));
handleContentLoad(event, enlace, this);
});
});
window.addEventListener('popstate', function() { loadContent(location.href, false); });
});
Explicación de los cambios realizados:
-
Evitar el uso de funciones flecha (arrow functions): Algunas versiones de navegadores no soportan las funciones flecha, lo que puede generar errores de sintaxis. Por ello, se sustituyeron todas las funciones flecha por funciones tradicionales.
-
Eliminar el operador de encadenamiento opcional (?.): Este operador no es compatible con todos los navegadores y puede producir errores de sintaxis. Se reemplazó this.querySelector('a')?.getAttribute('href') por (this.querySelector('a') && this.querySelector('a').getAttribute('href')).
-
Verificación de variables no definidas: Se añadió una verificación para asegurarse de que ajaxPage está definido antes de acceder a ajaxPage.logeado. Esto previene errores si ajaxPage no está disponible en el contexto global.
-
Conversión de plantillas literales a concatenación tradicional: En los casos donde se usaban plantillas literales para mensajes de consola, se cambiaron a concatenaciones con el operador + para garantizar compatibilidad.
-
Manejo de posibles elementos nulos: Se añadió una verificación para asegurarse de que contentElement existe antes de intentar acceder a su propiedad innerHTML. Esto evita errores si el elemento no se encuentra en el documento obtenido.
-
Retorno explícito en handleContentLoad: Al final de la función handleContentLoad, se añadió return false; para asegurarse de que la función devuelve un valor consistente y prevenir comportamientos inesperados.
Con estos cambios, el código debería funcionar correctamente sin generar errores de sintaxis. Asegúrate de probarlo en los navegadores que necesites soportar para verificar su funcionamiento.