javascript 如何使用javascript禁用浏览器中的后退按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19926641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to disable back button in browser using javascript
提问by A Beginner
Want to disable back button for a website
想要禁用网站的后退按钮
whenever the person click on browser back button it should not be able to go on the page he visited before.
每当此人单击浏览器后退按钮时,它都不应进入他之前访问过的页面。
采纳答案by geevee
You can't, and you shouldn't.
你不能,也不应该。
every other approach / alternative will only cause really bad user engagement.
所有其他方法/替代方案只会导致非常糟糕的用户参与。
that's my opinion.
这是我的意见。
回答by Shailendra Sharma
history.pushState(null, null, document.title);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.title);
});
This script will overwrite attempts to navigate back and forth with the state of the current page.
此脚本将覆盖尝试使用当前页面的状态来回导航。
Update:
更新:
Some users have reported better success with using document.URL
instead of document.title
:
一些用户报告说使用document.URL
而不是更好的成功document.title
:
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.URL);
});
回答by Joke_Sense10
One cannot disable the browser back button functionality only thing that can be done is prevent them.
不能禁用浏览器后退按钮功能,唯一可以做的就是阻止它们。
Below JavaScript code needs to be placed in the head section of the page where you don't want the user to revisit using the back button:
下面的 JavaScript 代码需要放置在您不希望用户使用后退按钮重新访问的页面的头部部分:
<script>
function preventBack(){window.history.forward();}
setTimeout("preventBack()", 0);
window.onunload=function(){null};
</script>
Suppose there are two pages Page1.php
and Page2.php
and Page1.php
redirects to Page2.php
.
假设有两个页面Page1.php
,Page2.php
并且Page1.php
重定向到Page2.php
。
Hence to prevent user from visiting Page1.php
using Back Button you will need to place the above script in the head section of Page1.php
.
因此,为了防止用户Page1.php
使用后退按钮访问,您需要将上述脚本放在Page1.php
.
For more info : Reference
更多信息:参考
回答by Horizon Consulting
Our approach is simple, but WORKS! :)
我们的方法很简单,但有效!:)
When a user clicks our LogOut button, we simply open the login page (or any page) and close the page we are one...simulating opening in new browser window w/ no history to go back to.
当用户单击我们的注销按钮时,我们只需打开登录页面(或任何页面)并关闭我们所在的页面......模拟在新浏览器窗口中打开而无需返回历史记录。
<input id="btnLogout" onclick="logOut()" class="btn btn-sm btn-warning" value="Logout" type="button"/>
<script>
function logOut() {
window.close = function () { window.open('Default.aspx', '_blank'); };
}
</script>