Search code examples
javascriptjquerysweetalert2

Sweetalert2: open external link in new tab on Yes


I implemented this survey pop-up using SweetAlert2. After 5 pageviews, the pop-up with Yes - No question apears after 3 seconds on page loaded.

The problem is I want the external url to be opened in a new tab / window. I already tried window.open(survey_url, '_blank');, but it has issues in IE. User must allow pop-ups and it seems the link is not opened.

Is there any better solution in sweetalert2 context? I mean having a simple button with link or something?

  $(document).ready(function($) {
    var survey_delay = 3000; // milliseconds
    var survey_delay_pageviews = 5;
    var survey_title = "This is a title!";
    var survey_text = "Would you be willing to say Yes?";
    var survey_url = "http://google.com";

    if(!localStorage.getItem("survey_answered")) {
      var pageviews = (+localStorage.getItem("page_views") || 0) + 1;
      localStorage.setItem("page_views", pageviews);

      if(pageviews >= survey_delay_pageviews) {
        setTimeout(function() {
          swal({
            title: survey_title,
            text: survey_text,
            type: "success",
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes',
            cancelButtonText: 'No'
          }).then(function(result) {
            localStorage.setItem("survey_answered", "true");
            window.location.replace(survey_url);
          }).catch(function() {
            localStorage.setItem("survey_answered", "true");
          });
        }, survey_delay);
      }
    }
  });

Solution

  • Solved by replacing the default button with link button with _blank target. Added just before my }, survey_delay); line:

      setTimeout(function () {
        $("button.swal2-confirm").replaceWith('<a target="_blank" class="swal2-confirm swal2-styled" style="background-color: rgb(48, 133, 214); border-left-color: rgb(48, 133, 214); border-right-color: rgb(48, 133, 214);" href="' + survey_url + '">Yes</a>');
        $("a.swal2-confirm").click(function () {
          localStorage.setItem("survey_answered", "true");
          swal.close()
        })
      }, 400);