【问题标题】:How can I disable body onload when the browser back button is used使用浏览器后退按钮时如何禁用正文加载
【发布时间】:2020-04-13 19:55:40
【问题描述】:

我们使用 body onload 函数来初始化表单上的选择 如果用户经常修改这些选择并提交表单,则希望单击返回以更改选择并再次提交表单。

当用户点击返回时,表单显然是从 onload 函数中重置。 我们希望用户能够使用返回按钮来查看他们选择的选项。

我们尝试了几种变量方法来运行一次并禁用提交按钮中的 onload。什么都没有成功。

有什么想法吗?

【问题讨论】:

    标签: onload back-button disable


    【解决方案1】:

    在清除表单之前尝试从您的 onload 函数中调用它:

    function isBackForward() {
      if (typeof performance === "object") {
        // Use the newer API if available.
        // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming
        if (typeof performance.getEntriesByType === "function") {
          var entries = performance.getEntriesByType("navigation");
          if (entries.length === 1) {
            if (entries[0].type === "back_forward") {
              return true;
            } else {
              return false;
            }
          } else {
            // unable to determine
            return void(0); // undefined
          }
        // Try the older deprecated API instead
        // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigation
        } else if (typeof performance.navigation === "object") {
          if (performance.navigation.type === performance.navigation.TYPE_BACK_FORWARD) {
            return true;
          } else {
            return false;
          }
        } else {
          // unable to determine
          return void(0); // undefined
        }
      } else {
        // unable to determine
        return void(0); // undefined
      }
    }
    

    如果使用后退或前进,此函数将返回 true,如果浏览器不支持确定所需的 api,则返回 undefined,如果是另一种导航类型,则返回 false。

    不幸的是,仅此一项在 Safari 中不起作用。对于 Safari,您可以在按下提交按钮时在 sessionStorage 中为页面设置一个状态值(参见https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage),然后在清除表单之前检查它。

    【讨论】:

      猜你喜欢
      • 2011-08-06
      • 2010-10-31
      • 2014-04-17
      • 2020-08-17
      • 2014-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多