通过js在新选项卡中有条件地打开url

Conditionally open url in new tab via js

本文关键字:有条件 url js 新选项 选项 通过      更新时间:2023-09-26

我有一个类似调查的web应用程序,用户可以在其中选择多个复选框,然后按下"提交"按钮,如链接

<!-- page: /survey -->
<form id="survey" method="post" action="/complete">
    <!-- checkboxes, etc here -->
    <a id="submit" class="button" href="#">Submit</a>
</form>
<script>
    $('#submit').on('click', function (e) {
        e.preventDefault();
        //... other staff happens here
        $('#survey').submit();
    });
</script>

然后在服务器上处理表单,并在/complete页面上向用户显示结果。

我想要实现的是在表单提交后有条件地打开一个新的选项卡。此条件和选项卡的url将在提交调查后在服务器上确定。

如果我将window.open('...', '_blank')插入初始/survey页面上的点击事件处理程序,我可以使其无条件工作:

$('#submit').on('click', function (e) {
    e.preventDefault();
    //... other staff happens here
    window.open('http://example.com', '_blank'); // <---- this line
    $('#survey').submit();
});

但是,如果我在/complete页面上使用window.open,它会失败:取而代之的是弹出警告。可能是因为它没有连接到任何用户启动的事件。

然而,在我的案例中,有一个用户启动的事件,但它发生在前一个页面上。有没有什么方法可以将此事件传递到新页面(显然新页面在同一域名、协议等上)。也许还有别的办法?

正确的方法是更改标记:

<form id="survey" method="post" action="/complete">
    <!-- checkboxes, etc here -->
    <button type="submit" id="submit" class="button">Submit</button>
</form>

然后在JavaScript中,监听submit事件。这将允许本机功能—例如隐式提交(在文本字段中输入键)或中键单击提交按钮—默认情况下工作。

下面是一些重要的部分:

  • 仅当输入无效时才阻止默认行为
  • 如果希望在新选项卡中打开表单,请更改表单的target属性
$('#survey').on('submit', function (e) {
    if (!checkValidity(...)) {
        e.preventDefault();
        return;
    }
    //other stuff happens
    var newTab = shouldOpenInNewTab(...);
    $(this).attr('target', newTab ? '_blank' : '');
});

这样做将允许浏览器使用其默认行为。它与跨浏览器兼容,并且可以访问。