Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
Copa WPB
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Cómo mostrar ventana emergente de confirmación de navegación para formularios en WordPress

Nota editorial: Ganamos una comisión de los enlaces de socios en WPBeginner. Las comisiones no afectan a las opiniones o evaluaciones de nuestros editores. Más información sobre Proceso editorial.

Cerrar accidentalmente una página sin enviar tu comentario o con un formulario a medio rellenar es molesto. Recientemente, uno de nuestros usuarios nos preguntó si era posible mostrar a sus lectores un mensaje / ventana emergente de confirmación de navegación.

Esta pequeña ventana emergente alerta a los usuarios y evita que dejen accidentalmente formularios a medio rellenar y sin enviar. Es una buena forma de mejorar la experiencia del usuario y evitar que los visitantes tengan que empezar algo desde cero.

En este artículo, le mostraremos cómo mostrar confirmar ventana emergente de navegación para los formularios de WordPress.

Confirm navigation popup when user leaves a form unsubmitted

¿Qué es una ventana emergente de confirmación de navegación?

Supongamos que un usuario está escribiendo un comentario en tu blog. Ya han escrito unas cuantas líneas, pero se distraen y se olvidan de enviar los comentarios. Ahora bien, si cierran el navegador / explorador, el comentario se perderá.

La ventana emergente de confirmación de navegación les da la oportunidad de terminar su comentario.

Puede ver esta característica en acción en la pantalla del editor de entradas de WordPress. Si tiene cambios sin guardar e intenta salir de la página o cerrar el navegador, verá un mensaje / ventana emergente de advertencia.

Unsaved changes warning popup in WordPress post editor

Veamos cómo podemos añadir esta característica de advertencia a los comentarios de WordPress y a otros formularios de tu sitio:

Mostrar ventana emergente de Confirmación de Navegación para Formularios no Enviados en WordPress

Para este tutorial, vamos a crear un plugin personalizado, pero no te preocupes, también puedes descargar el plugin al final de este tutorial para instalarlo en tu sitio web.

Sin embargo, para una mejor comprensión del código, le pediremos que intente crear su propio plugin. Puede hacerlo primero en una instalación local o en un sitio de ensayo.

Primeros pasos.

Primero, necesitas crear una nueva carpeta en tu ordenador y llamarla confirm-leaving. Dentro de la carpeta confirm-leaving, tienes que crear otra carpeta y llamarla js.

Ahora abre un editor de texto plano como Notepad y crea un nuevo archivo. Dentro, simplemente pegue el siguiente código:

[php]
<?php
/**
 * Confirm Leaving
 * Plugin Name: Confirm Leaving
 * Plugin URI:  https://www.wpbeginner.com
 * Description: This plugin shows a warning to users when try they forget to hit submit button on a comment form.
 * Version:     1.0.0
 * Author:      WPBeginner
 * Author URI:  https://www.wpbeginner.com
 * License:     GPL-2.0+
 * License URI: http://www.gnu.org/licenses/gpl-2.0.txt
 */

function wpb_confirm_leaving_js() { 

     wp_enqueue_script( 'Confirm Leaving', plugins_url( 'js/confirm-leaving.js', __FILE__ ), array('jquery'), '1.0.0', true );
}
add_action('wp_enqueue_scripts', 'wpb_confirm_leaving_js');
[/php]

Esta función PHP simplemente añade un archivo JavaScript a la parte frontal de su sitio web.

Guarda este archivo confirm-leaving.php dentro de la carpeta principal de confirm-leaving.

Ahora, necesitamos crear el archivo JavaScript que este plugin está cargando.

Crea un nuevo archivo y pega este código en él:

[javascript]
jQuery(document).ready(function($) { 

$(document).ready(function() {
    needToConfirm = false;
    window.onbeforeunload = askConfirm;
});

function askConfirm() {
    if (needToConfirm) {
        // Put your custom message here
        return "Your unsaved data will be lost.";
    }
}

$("#commentform").change(function() {
    needToConfirm = true;
});

 })
[/javascript]

Este código JavaScript detecta si el usuario tiene cambios sin guardar en el formulario de comentarios. Si un usuario intenta navegar fuera de la página o cerrar la ventana, mostrará una ventana emergente de advertencia.

Debes guardar este archivo como confirm-leaving.js dentro de la carpeta js.

Después de guardar ambos archivos, ésta es la estructura de carpetas:

Plugin file structure

Ahora, necesitas conectarte a tu sitio WordPress usando un cliente FTP. Consulte nuestra guía sobre cómo utilizar FTP para subir archivos de WordPress.

Una vez conectado, es necesario subir confirmar dejando la carpeta a /wp-contents/plugins/ la carpeta en su sitio web.

Uploading plugin files to your WordPress site

Después, deberá acceder al área de administrador de WordPress y visitar la página del plugin.

Localice el plugin “Confirmar salida” en la lista de plugins instalados y haga clic en el enlace “activar” que aparece debajo.

Activate plugin

Eso es todo. Ahora puede visitar cualquier entrada de su sitio web, escribir un texto en cualquier campo del formulario de comentarios y, a continuación, intentar salir de la página sin enviar el comentario.

Aparecerá un mensaje / ventana emergente, advirtiéndole de que está a punto de abandonar una página con cambios no guardados.

popup notification warning user about unsaved changes

Añadir la advertencia a otros formularios en WordPress

Puede utilizar el mismo código base para cualquier formulario de su sitio WordPress. Aquí, le mostraremos un ejemplo de su uso para orientar un formulario de contacto.

En este ejemplo, estamos utilizando el plugin WPForms para crear un formulario de contacto. Las instrucciones serán las mismas si está utilizando un plugin de formulario de contacto diferente en su sitio web.

Vaya a la página donde ha añadido su formulario de contacto. Sitúe el ratón sobre el primer campo del formulario de contacto, haga clic con el botón derecho y seleccione “Inspeccionar” en el menú del navegador.

Finding form ID

Localice la línea que comienza con la etiqueta <form>. En la etiqueta de formulario, encontrará el atributo ID.

En este ejemplo, el ID de nuestro formulario es wpforms-form-170. Es necesario copiar el atributo ID.

Ahora edita el archivo confirm-leaving.js y añade el atributo ID después de #commentform.

Asegúrate de separar #commentform del ID de tu formulario con una coma. También tendrás que añadir un signo # como prefijo al atributo ID de tu formulario.

Tu código tendrá ahora este aspecto:

[javascript]
jQuery(document).ready(function($) { 

$(document).ready(function() {
    needToConfirm = false;
    window.onbeforeunload = askConfirm;
});

function askConfirm() {
    if (needToConfirm) {
        // Put your custom message here
        return "Your unsaved data will be lost.";
    }
}

$("#commentform,#wpforms-form-170").change(function() {
    needToConfirm = true;
});

 })
[/javascript]

Guarda los cambios y vuelve a subir el archivo a tu sitio web.

Ahora, puede introducir cualquier texto en cualquier campo de su formulario de contacto y luego intentar salir de la página sin enviar el formulario. Aparecerá un mensaje / ventana emergente con una advertencia de que tiene cambios sin guardar.

Puede descargar el plugin de confirmación de abandono aquí. Solo se dirige al formulario de comentarios, pero no dudes en editar el plugin para dirigirlo a otros formularios.

Eso es todo; esperamos que este artículo te haya ayudado a mostrar el mensaje / ventana emergente de navegación de confirmación para formularios de WordPress. También puede marcar / comprobar nuestra debe tener plugins de WordPress y herramientas para sitios de negocios o leer nuestra guía definitiva sobre cómo aumentar el tráfico de su blog.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Descargo: Nuestro contenido está apoyado por los lectores. Esto significa que si hace clic en algunos de nuestros enlaces, podemos ganar una comisión. Vea cómo se financia WPBeginner , por qué es importante, y cómo puede apoyarnos. Aquí está nuestro proceso editorial .

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

El último kit de herramientas de WordPress

Obtenga acceso GRATUITO a nuestro kit de herramientas - una colección de productos y recursos relacionados con WordPress que todo profesional debería tener!

Reader Interactions

20 comentariosDeja una respuesta

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Igor says

    Tried to use your code in bbpress forum. Unfortunately no popup message appears after user dose not post his comment. Tried all variations of changing id in JS file but still nothing appears.

  3. Bob Garrett says

    Further to my previous query I have now tried using the form’s parent div id and modified the code. This almost works but…

    The text shown by the pop-up is not the text entered in the code.

    Even if the form is completed and submit hit, then going to another page still results in the warning.

    How can I resolve this?

  4. Tom Kelley says

    Have tried this vvvvv to no avail. Working with Gravity Forms. All else works well, but the warning still comes up when hitting the submit button on a completed form. Any advice?

    WPBeginner Support
    Nov 27, 2016 at 6:52 am

    Hi Bonnie,

    We tested the plugin with WPForms and it worked. You will need to edit the confirm-leaving.js file and replace #commentform with the wpforms container div id. Typically it is wpforms-12 where 12 is the ID of your form. You can also see it using the inspect element tool in your browser.

    • Bonnie Ramthun says

      I’m still trying to figure out how to make sure the popup DOESN’T appear when the user presses the “Submit” button. The confirm leaving popup shouldn’t appear if the user has entered all the information required, but this code makes it pop up every time.

      I would so appreciate the help, if there is a solution available.

  5. Swayam Dhawan says

    I Need the same function when someone navigate from particular page in website and while click on stay , they must navigate to home page of the website.

    waiting for the response.

  6. Bonnie Ramthun says

    I am so happy for your wonderful confirm navigation code! I need it desperately because many of my clients users can’t get it through their head that they need to press the “Submit” button on the form.

    The code works perfectly, except for one problem. When I press the “Submit” button on my WPForms form, the confirm navigation code pops up. I would like the “confirm navigation” to happen only when the user doesn’t press the “Submit” button. I can’t figure out how to do this. Can you help?

    • WPBeginner Support says

      Hi Bonnie,

      We tested the plugin with WPForms and it worked. You will need to edit the confirm-leaving.js file and replace #commentform with the wpforms container div id. Typically it is wpforms-12 where 12 is the ID of your form. You can also see it using the inspect element tool in your browser.

      Administrador

  7. Will C says

    I have two separate multi-page gravity forms on my site. When this plugin is active, I get a confirmation popup when clicking “Next Step” on one of the forms (undesired), but not the other. Are you aware of any issues with gravity forms and “window.onbeforeunload”? Thanks

      • Nipa Sarker says

        I ma using the code for buddy-press multi step create group from.It is working fine except while clicking on the next step button or save button it is showing the same alert.
        I ma using the form id “#create-group-form” instead of the #commentform

  8. Luis Zarza says

    Hi, nice post!

    It helped a lot. But your solution won’t work while logged in. It only works for users that fill in the form and are logged out. I need it also to work for logged in users, please!
    Could you provide a solution for that?

    Thanks.

    • Luis Zarza says

      Sorry, it does actually works when you create the plugin. At first I did it only throwing the JS to the page I wanted without creating the plugin, because I didn’t want the script to be loaded on all the pages of my site.

  9. Betty L Van Fossen says

    I have two problems. One I get these pop up in my mail all the time,q it’s aggravating. I’m 89 in yrs.therefore a little short on patience and I start using my pointer to fast hitting other things, so I get myself in lots of problems. Two –guess(I know) I have to many cookies they say. What are the cookies –how do I eleminate them? What do you mean subscribe without commenting. I prefer the e-mail. O.K..to personal and meaningful conversation.

        • Betty L Van Fossen says

          Safari said I could not get in cause I had to many cookies. In the meantime I was on my e-mail and the pop ups came on, while on my e-mail they are always popping up. I got on google and asked for help on cookies and pop ups and gave me lots to choose from. Now word press got in here, what is word press. I’m not going to write a book,just NEED HELP. Answer by e-mail. I’m turning you off now I’m really tired now.

Deja tu comentario

Gracias por elegir dejar un comentario. Tenga en cuenta que todos los comentarios son moderados de acuerdo con nuestros política de comentarios, y su dirección de correo electrónico NO será publicada. Por favor, NO utilice palabras clave en el campo de nombre. Tengamos una conversación personal y significativa.