拦截我的 AJAX 应用程序中返回按钮的调用

86

我有一个 AJAX 应用程序。用户点击按钮后,页面的显示会更改。他们单击返回按钮,希望返回到原始状态,但实际上,他们回到了浏览器中的前一页。

如何拦截并重新指定返回按钮事件?我已经研究了像 RSH 这样的库(但我无法让它工作...),我听说使用哈希标签可以在某种程度上帮助,但我搞不懂。

13个回答

0

两种简单的不同方法。

Performance.getEntriesByType将返回“reload”、“navigation”、“back_forward”或“prerender”,然后您可以使用if else创建条件语句;

performance.getEntriesByType("navigation").forEach((entry) => {
    console.log(entry.type)
});

Cookies;

var HisLen = getCookie("HisLen");
if (HisLen == history.length) {
    console.log("Back or forward or reload button clicked");
}
setTempCookies("HisLen", history.length, 1000 * 3600);

0
如果您使用React,可以使用NPM模块:use-history-back-trap。这是一个自定义的React钩子,拦截后退导航并允许稍后恢复它(如果需要)。或者在“approveNavigation”中执行其他操作(如导航到另一个地方)。

使用方法非常简单:

const SomeFunctionalReactComponent = () => {
   useHistoryBackTrap(approveNavigation)
   // ...
}

其中approveNavigation是您的函数,当您想要进行后退导航时返回true(或Promise)。


0
@gitaarik有答案,但不幸的是没有提供示例。

这里是一个最小工作示例,演示如何使用历史API防止用户在点击后退按钮时返回到上一页:

const button = document.getElementById('button');
const display = document.getElementById('display');
button.addEventListener('click', populateDisplay);

// fired after user hits back button (see popstate docs linked below) 
window.addEventListener('popstate', clearDisplay);

function populateDisplay() {
  display.textContent = 'hit the browser\'s back button to clear';
  
  // add state to history stack, as if you're visiting a new page
  const state = {something: 'useful'};
  history.pushState(state, '', '#display-populated');
}

function clearDisplay() {
  display.textContent = '';
}
#button {
  /* only cosmetic */
  padding: 20px;
  background-color: lightsteelblue;
}
<div id="button">click me</div>
<div id="display"></div>

这个示例中实际上并没有使用state对象。除其他用途外,它可以在导航离开后用于恢复页面状态,如此处所示。

还可以参考Mozilla的文档,解释了何时触发popstate事件


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接