#191 - Browser Compatibility Notice v0.1

Automatically detect outdated browsers and display a dismissible notice.

Ver demostración


<!-- 💙 MEMBERSCRIPT #191 v0.1 💙 - BETTER BROWSER COMPATIBILITY NOTICES -->

<script>

(function() {

  'use strict';

  // ═══════════════════════════════════════════════════════════════

  // CONFIGURATION

  // ═══════════════════════════════════════════════════════════════

  const CONFIG = {
    // Minimum supported browser versions
    MIN_VERSIONS: {
      chrome: 90,
      firefox: 88,
      safari: 14,
      edge: 90,
      opera: 76
    },
    // Messages for different browser types
    MESSAGES: {
      outdated: 'Your browser is outdated and may not support all features. Please update for the best experience.',
      unsupported: 'Your browser is not fully supported. Please use a modern browser like Chrome, Firefox, Safari, or Edge.',
      update: 'Update your browser',
      dismiss: 'Dismiss'
    },
    // Show notice even if dismissed (for testing)
    // Set to true to always show the notice, regardless of browser or dismissal state
    FORCE_SHOW: false,
    // Storage key for dismissed state
    STORAGE_KEY: 'ms_browser_notice_dismissed'
  };

  

  // ═══════════════════════════════════════════════════════════════

  // BROWSER DETECTION

  // ═══════════════════════════════════════════════════════════════

  function getBrowserInfo() {
    const ua = navigator.userAgent;
    let browser = { name: 'unknown', version: 0 };

    

    // Internet Explorer (all versions unsupported)
    if (/MSIE|Trident/.test(ua)) {
      return { name: 'ie', version: 0, unsupported: true };
    }

    

    // Chrome
    const chromeMatch = ua.match(/Chrome\/(\d+)/);
    if (chromeMatch && !/Edg|OPR/.test(ua)) {
      return { name: 'chrome', version: parseInt(chromeMatch[1], 10) };
    }

    

    // Edge (Chromium-based)
    const edgeMatch = ua.match(/Edg\/(\d+)/);
    if (edgeMatch) {
      return { name: 'edge', version: parseInt(edgeMatch[1], 10) };
    }

    

    // Legacy Edge (unsupported)
    if (/Edge\/\d/.test(ua) && !/Edg/.test(ua)) {
      return { name: 'edge-legacy', version: 0, unsupported: true };
    }

    

    // Firefox
    const firefoxMatch = ua.match(/Firefox\/(\d+)/);
    if (firefoxMatch) {
      return { name: 'firefox', version: parseInt(firefoxMatch[1], 10) };
    }

    

    // Safari (must check for Chrome first to avoid false positives)
    const safariMatch = ua.match(/Version\/(\d+).*Safari/);
    if (safariMatch && !/Chrome|Chromium/.test(ua)) {
      return { name: 'safari', version: parseInt(safariMatch[1], 10) };
    }

    

    // Opera
    const operaMatch = ua.match(/OPR\/(\d+)/);
    if (operaMatch) {
      return { name: 'opera', version: parseInt(operaMatch[1], 10) };
    }

    

    return browser;
  }

  

  function isBrowserOutdated(browser) {
    // Unsupported browsers (IE, legacy Edge)
    if (browser.unsupported) {
      return { outdated: true, reason: 'unsupported' };
    }

    

    // Unknown browser
    if (browser.name === 'unknown') {
      return { outdated: false, reason: 'unknown' };
    }

    

    // Check against minimum versions
    const minVersion = CONFIG.MIN_VERSIONS[browser.name];
    if (minVersion && browser.version < minVersion) {
      return { outdated: true, reason: 'outdated', current: browser.version, required: minVersion };
    }

    

    return { outdated: false, reason: 'supported' };
  }

  

  // ═══════════════════════════════════════════════════════════════

  // STORAGE HELPERS

  // ═══════════════════════════════════════════════════════════════

  function isDismissed() {
    if (CONFIG.FORCE_SHOW) return false;
    try {
      return localStorage.getItem(CONFIG.STORAGE_KEY) === 'true';
    } catch (e) {
      return false;
    }
  }

  

  function setDismissed() {
    try {
      localStorage.setItem(CONFIG.STORAGE_KEY, 'true');
    } catch (e) {
      // Silently fail if localStorage is not available
    }
  }

  

  // ═══════════════════════════════════════════════════════════════

  // NOTICE DISPLAY

  // ═══════════════════════════════════════════════════════════════

  function getBrowserUpdateUrl(browserName) {
    const urls = {
      chrome: 'https://www.google.com/chrome/',
      firefox: 'https://www.mozilla.org/firefox/',
      safari: 'https://www.apple.com/safari/',
      edge: 'https://www.microsoft.com/edge',
      opera: 'https://www.opera.com/download',
      'edge-legacy': 'https://www.microsoft.com/edge',
      ie: 'https://www.microsoft.com/edge'
    };
    return urls[browserName] || 'https://browsehappy.com/';
  }

  

  function createNotice(browser, status) {
    // Only works with custom Webflow-designed container
    const customContainer = document.querySelector('[data-ms-code="browser-notice"]');
    if (!customContainer) {
      return;
    }

    

    // Show the container (override CSS display:none if set in Webflow)
    const computedStyle = window.getComputedStyle(customContainer);
    if (computedStyle.display === 'none' || customContainer.style.display === 'none') {
      // Set explicit display value to override CSS rule
      // Use 'block' as default, or preserve original if it was set via inline style
      customContainer.style.setProperty('display', 'block', 'important');
    }

    

    // Populate individual elements within the container
    const messageEl = customContainer.querySelector('[data-ms-code="browser-notice-message"]');
    const updateLinkEl = customContainer.querySelector('[data-ms-code="browser-notice-update"]');
    const dismissBtnEl = customContainer.querySelector('[data-ms-code="browser-notice-dismiss"]');

    

    // Populate message
    if (messageEl) {
      const isUnsupported = status.reason === 'unsupported';
      messageEl.textContent = isUnsupported ? CONFIG.MESSAGES.unsupported : CONFIG.MESSAGES.outdated;
    }

    

    // Populate update link
    if (updateLinkEl) {
      const updateUrl = getBrowserUpdateUrl(browser.name);
      // Handle both <a> tags and other elements
      if (updateLinkEl.tagName.toLowerCase() === 'a') {
        updateLinkEl.href = updateUrl;
        updateLinkEl.setAttribute('target', '_blank');
        updateLinkEl.setAttribute('rel', 'noopener noreferrer');
      } else {
        // For buttons or other elements, add onclick
        updateLinkEl.onclick = function(e) {
          e.preventDefault();
          window.open(updateUrl, '_blank', 'noopener,noreferrer');
        };
      }
      updateLinkEl.textContent = CONFIG.MESSAGES.update;
    }

    

    // Populate dismiss button
    if (dismissBtnEl) {
      dismissBtnEl.textContent = CONFIG.MESSAGES.dismiss;
      attachDismissHandler(customContainer);
    }

    

    return customContainer;
  }

  

  function attachDismissHandler(container) {
    const dismissBtn = container.querySelector('[data-ms-code="browser-notice-dismiss"]');
    if (dismissBtn) {
      dismissBtn.addEventListener('click', function() {
        setDismissed();
        // Hide container using Webflow's own styling
        container.style.display = 'none';
      });
    }
  }

  

  // ═══════════════════════════════════════════════════════════════

  // INITIALIZATION

  // ═══════════════════════════════════════════════════════════════

  function init() {
    // Check if custom container exists (designed in Webflow)
    const customContainer = document.querySelector('[data-ms-code="browser-notice"]');
    if (!customContainer) {
      return;
    }

    

    // Hide banner if already dismissed (unless force show)
    if (isDismissed() && !CONFIG.FORCE_SHOW) {
      customContainer.style.display = 'none';
      return;
    }

    

    // Wait for DOM to be ready
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', checkAndShowNotice);
    } else {
      checkAndShowNotice();
    }
  }

  

  function checkAndShowNotice() {
    const browser = getBrowserInfo();
    const status = isBrowserOutdated(browser);

    

    const customContainer = document.querySelector('[data-ms-code="browser-notice"]');

    

    if (status.outdated || CONFIG.FORCE_SHOW) {
      createNotice(browser, status);
    } else {
      // Hide banner if browser is up to date
      if (customContainer) {
        customContainer.style.display = 'none';
      }
    }
  }

  

  // Start initialization
  init();
})();

</script>

Customer Showcase

Have you used a Memberscript in your project? We’d love to highlight your work and share it with the community!

Creación del escenario Make.com

1. Descargue el proyecto JSON a continuación para empezar.

2. Navegue hasta Make.com y Cree un nuevo escenario...

3. Haga clic en el pequeño cuadro con 3 puntos y luego Importar Blueprint...

4. Sube tu archivo y ¡voilá! Ya está listo para vincular sus propias cuentas.

¿Necesitas ayuda con este MemberScript?

Todos los clientes de Memberstack pueden solicitar asistencia en el Slack 2.0. Tenga en cuenta que no se trata de funciones oficiales y que no se puede garantizar la asistencia.

Únete al Slack 2.0
Notas de la versión
Atributos
Descripción
Atributo
No se han encontrado artículos.
Guías / Tutoriales
No se han encontrado artículos.
Tutorial
¿Qué es Memberstack?

Autenticación y pagos para sitios Webflow

Añada inicios de sesión, suscripciones, contenido cerrado y mucho más a su sitio Webflow: fácil y totalmente personalizable.

Más información

"Hemos estado utilizando Memberstack durante mucho tiempo, y nos ha ayudado a lograr cosas que nunca hubiéramos creído posible usando Webflow. Nos ha permitido construir plataformas con gran profundidad y funcionalidad y el equipo que hay detrás siempre ha sido súper servicial y receptivo a los comentarios"

Jamie Debnam
39 Digital

"He estado construyendo un sitio de membresía con Memberstack y Jetboost para un cliente. Se siente como magia construir con estas herramientas. Como alguien que ha trabajado en una agencia donde algunas de estas aplicaciones fueron codificadas desde cero, finalmente entiendo el bombo ahora. Esto es mucho más rápido y mucho más barato."

Félix Meens
Estudio Webflix

"Uno de los mejores productos para iniciar un sitio de membresía - Me gusta la facilidad de uso de Memberstack. Yo era capaz de mi sitio de membresía en marcha y funcionando dentro de un día. No hay nada más fácil que eso. También proporciona la funcionalidad que necesito para hacer la experiencia del usuario más personalizada."

Eric McQuesten
Nerds de la tecnología sanitaria
Depósito Off World

"Mi negocio no sería lo que es sin Memberstack. Si crees que 30 $/mes es caro, prueba a contratar a un desarrollador para que integre recomendaciones personalizadas en tu sitio por ese precio. Increíblemente flexible conjunto de herramientas para aquellos dispuestos a poner en algunos esfuerzos mínimos para ver su documentación bien elaborado."

Riley Brown
Depósito Off World

"La comunidad de Slack es una de las más activas que he visto y los clientes están dispuestos a responder preguntas y ofrecer soluciones. He realizado evaluaciones en profundidad de herramientas alternativas y siempre volvemos a Memberstack: ahórrate el tiempo y dale una oportunidad"."

Abadía Burtis
Nerds de la tecnología sanitaria
Slack

¿Necesitas ayuda con este MemberScript? ¡Únete a nuestra comunidad Slack!

Únete al Slack de la comunidad Memberstack y ¡pregunta! Espera una respuesta rápida de un miembro del equipo, un experto de Memberstack o un compañero de la comunidad.

Únete a nuestro Slack