用于在表单提交上设置 cookie 的 JS 在 Firefox 中有效,但在 Edge/Chrome 中无效

JS for setting cookies on Form Submit works in Firefox but not Edge/Chrome

我有一个 bootstrap 模式,它会在页面加载时弹出,要求用户设置他们的位置并将此值保存到 cookie。

这在 Firefox 中一切正常,但在 Edge 或 Chrome 中不起作用。有人有什么想法吗?

<script>
function setCookie(cookieName, cookieValue, nDays) {
    
    var today = new Date();
    var expire = new Date();

    if (!nDays) 
        nDays=1;
    expire.setTime(today.getTime() + 3600000*24*nDays);
    document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
    return false
}
</script>

<div class="modal_container">
     
        <!-- Modal -->
        <div class="modal fade" id="store_prompt" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title" id="exampleModalLongTitle">Location Number</h5>
                </div>
                <div class="modal-body">
                    <form onsubmit="javascript:return setCookie('location', this.querySelector('select').value, 365);">
                        <div class="form-group">
                            <label for="LocationSelect">Please select your location below.</label>
                            <select class="form-control" id="LocationSelect">
                              <option value='1' >1 - Location A</option>
                              <option value='2' >2 - Location B</option>
                            </select>
                        </div>
                        <button type="submit" class="btn btn-primary btn-lg btn-block" onclick="closemodal(); location.reload();">Save changes</button>
                    </form> 
                </div>
              </div>
            </div>
</div>

我认为这可能是因为这个问题中提到的问题。请通过这些。它可能会解决您的问题。 Why would setting document.cookie not work in Chrome?

您是否像file:///C:/...一样通过文件协议测试代码?如果是这样,我可以重现你遇到的情况。

你的代码是正确的。但使用 file:/// 协议浏览时,cookie 不会被设置,具体取决于浏览器。您需要在 http/https 服务器上 运行 您的页面,然后代码才能在所有浏览器上运行。

结果: