首页 > 解决方案 > Sweetalert2:在新选项卡中打开外部链接是

问题描述

我使用SweetAlert2实现了这个调查弹出窗口。浏览 5 次后,在页面加载 3 秒后会出现带有 Yes - No question 的弹出窗口。

问题是我希望在新选项卡/窗口中打开外部 url。我已经试过了window.open(survey_url, '_blank');,但它在 IE 中存在问题。用户必须允许弹出窗口,并且链接似乎没有打开。

在 sweetalert2 上下文中是否有更好的解决方案?我的意思是有一个带有链接或其他东西的简单按钮?

  $(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);
      }
    }
  });

标签: javascriptjquerysweetalert2

解决方案


通过将默认按钮替换为带有_blank目标的链接按钮来解决。}, survey_delay);在我的行之前添加:

  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);

推荐阅读