簡體   English   中英

如果存在查詢字符串,則觸發 javascript 函數

[英]Fire off javascript function if query string is present

所以我有一個表單,一旦提交成功,我就會使用它,它會向 URL 添加一個?success查詢字符串。

使用以下代碼,每當用戶到達?success頁面時,它將阻止他們點擊后退按鈕,這有助於防止提交到數據庫 - 問題是,如果我有服務器端錯誤,它將阻止后退按鈕整個頁面,直到清除緩存。

在此處輸入圖片說明

function disableBack() {
    window.history.forward()
}

window.onload = disableBack();
window.onpageshow = function(evt) {
    if (evt.persisted)
        evt.preventDefault();
    disableBack()
};

一旦僅存在?success查詢字符串,如何使以下 javascript 代碼段觸發? 我試過下面的代碼,但沒有運氣:

if (location.search === "?success") {
    // Prevent the form from being resubmitted on backspace
    function disableBack() {
        window.history.forward()
    }

    window.onload = disableBack();
    window.onpageshow = function(evt) {
        if (evt.persisted)
            evt.preventDefault();
        disableBack()
    };
}

更新的答案(它仍然重定向回來):

function disableBack() {
    window.history.forward()
}

var includesURLSearchString = searchString => location.search.includes(searchString);
var hasQueryString = includesURLSearchString('success');

console.log(hasQueryString);

if (hasQueryString) {

    // Prevent the form from being resubmitted on backspace
    window.onload = disableBack();
    window.onpageshow = function (evt) {
    if (evt.persisted)
        evt.preventDefault();
        disableBack()
    };
}

location.search有一個字符串作為值。 您可以使用includes方法檢查字符串是否包含某個單詞。 考慮下面的函數。

const includesURLSearchString = searchString => location.search.includes(searchString);

您可以使用此函數來檢查是否在location.search字符串中找到了諸如search之類的詞。 所以?site=something&success將返回true

const hasQueryString = includesURLSearchString('success');
if (hasQueryString) {
  disableBack();
}

編輯

URLSearchParams接口旨在用於此目的。 您可以使用此 API 來解構查詢字符串,而不是創建自己的檢查字符串的函數。 使用has方法,您可以檢查值是否存在。

const searchParams = new URLSearchParams(location.search);
const hasQueryString = searchParams.has('success');
if (hasQueryString) {
  disableBack();
}

如果您嘗試禁用瀏覽器的back按鈕,請嘗試以下操作。 此函數將以編程方式將 URL 添加到瀏覽器的歷史記錄中。 每當用戶嘗試返回時, popstate觸發popstate事件。 每當在 JS 中添加的狀態history刪除時,就會觸發此事件。 現在,每當用戶返回時,它只需將當前 URL 再次添加到歷史記錄中。 所以用戶永遠無法返回。

帶有此解決方案的原始帖子:

function disableBack() {
  history.pushState(null, null, location.href);
  window.addEventListener('popstate', function () {
    history.pushState(null, null, location.href);
  });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM