Javascript 禁用一页应用程序的浏览器后退按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31308958/
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
Disable browser back button for one page application
提问by Developer107
I need to disable the back button of browser in my single page application. I tried using methods like onhashchangeor window.history.forwardbut they don't work (reason may be that url doesn't get changed here) Please help! Thanks.
我需要在我的单页应用程序中禁用浏览器的后退按钮。我尝试使用诸如onhashchange或window.history.forward 之类的方法,但它们不起作用(原因可能是此处未更改 url) 请帮助!谢谢。
回答by relizondo6
I work in AngularJS building a Single Page App and I wanted to disable or prevent the back button of the browser, because my app has buttons and anchors for all navegation into my app.
我在 AngularJS 中构建了一个单页应用程序,我想禁用或阻止浏览器的后退按钮,因为我的应用程序有按钮和锚点,用于所有导航到我的应用程序。
I searched and test many codes, and this is the easy to prevent the back button of browsers and the following code worked for me.
我搜索并测试了许多代码,这是防止浏览器后退按钮的简单方法,以下代码对我有用。
window.onpopstate = function (e) { window.history.forward(1); }
window.onpopstate = function (e) { window.history.forward(1); }
When the history detects the first history.back()
当历史检测到第一个 history.back()
window.onpopstate
window.onpopstate
is executed, then after this moment any back or forward in history are detected for onpopstate event.
执行,然后在这一刻之后,检测到历史中的任何后退或前进的 onpopstate 事件。
回答by Viraj Nalawade
回答by Shekhar
You technically cannot disable the Back button on someone's browser, however, you can make it so that the button isn't available or continues to load the same page.
从技术上讲,您无法禁用某人浏览器上的“后退”按钮,但是,您可以将其设置为不可用或继续加载同一页面。
You can check it here Disabling the Back Button
您可以在此处查看禁用后退按钮
回答by Ellanki samba siva
import { LocationStrategy } from '@angular/common';
constructor( private location: LocationStrategy){
// preventing back button in browser implemented by "Samba Siva"
history.pushState(null, null, window.location.href);
this.location.onPopState(() => {
history.pushState(null, null, window.location.href);
});
}
回答by Deepesh kumar
You can redirect same page on click of back button, your page will get refreshed but you will be on the same page every time
您可以通过单击后退按钮重定向同一页面,您的页面会刷新,但您每次都会在同一页面上
回答by Deivi
i think the "onpopstate" dont work if the user persist click
我认为如果用户坚持点击“onpopstate”不起作用
just use
只是使用
window.onbeforeunload = function() { window.history.forward(1); };
or if u like to warning user
或者如果你想警告用户
window.onbeforeunload = function() { return "Back button is not available!"; window.history.forward(1); };
回答by Viorel Mateianu
If you're using AngularJS, the following code should do the trick. You have to add this code to app.js file or file where you inject all your dependencies
如果您使用的是 AngularJS,下面的代码应该可以解决问题。您必须将此代码添加到 app.js 文件或注入所有依赖项的文件中
var myApp = angular.module('myApp', ['ngMask', 'ngRoute', 'ngAnimate', 'ngSanitize', 'ngTouch', 'ngCookies', 'ngMessages', 'ui.router', 'ui.grid', 'ui.directives', 'ui.filters', 'ui.bootstrap', 'angularUtils.directives.dirPagination']);
myApp.run(function($rootScope, $route, $location) {
var allowNav = false;
var checkNav = false;
$rootScope.$on('$stateChangeSuccess', function (event, toState, toStateParams, fromState, fromStateParams) {
allowNav = checkNav;
checkNav = true;
});
$rootScope.$on('$locationChangeStart', function (event, next, current) {
// Prevent the browser default action (Going back)
if (checkNav) {
if (!allowNav) {
event.preventDefault();
} else {
allowNav = false;
}
}
});
});
回答by DeadlyChambers
I had a different scenario where we wanted to blacklist a few pages. Allowing most of the SPA to use the back button and a few pages to not allow it. I created a service to override the functionality of the popstate. However I ran into a weird issue with going forward.
我有一个不同的场景,我们想将一些页面列入黑名单。允许大部分 SPA 使用后退按钮,少数页面不允许使用。我创建了一个服务来覆盖 popstate 的功能。但是,我在前进时遇到了一个奇怪的问题。
import { RouteAddress } from 'app/common/constants/routes.constants';
import { Injectable } from '@angular/core';
import { StringUtilsService } from 'app/common/services/utilities/string-utils.service';
@Injectable()
export class LocationStrategyService {
private static shouldSkip = false;
// Array of route urls that we can't go back to.
private static blackListed = [
RouteAddress.ScreeningStepTwoCreditAvailability,
RouteAddress.ScreeningStepTwo];
constructor() {
window.onpopstate = this.overridingPopState;
}
overridingPopState(event: any) {
// This was having issue scoping
const isBlackListed = (navigatingTo: string): boolean => {
navigatingTo = navigatingTo.split('?')[0];
const pathFound = LocationStrategyService.blackListed.find((route) => navigatingTo.endsWith('/' + route));
return pathFound !== undefined && pathFound.length > 0;
}
// have black listed route and determing if able to go back
if (!LocationStrategyService.shouldSkip && isBlackListed(event.currentTarget.location.pathname)) {
window.history.forward();
// Protecting against a going forward that will redirect
LocationStrategyService.shouldSkip = isBlackListed(window.location.pathname);
} else {
LocationStrategyService.shouldSkip = false;
}
}
}
Then in your AppComponent constructor add the LocationStrategyService and it will call it on start.
然后在您的 AppComponent 构造函数中添加 LocationStrategyService,它会在启动时调用它。
import { LocationStrategyService } from 'app/common/services/utilities/location-strategy.service';
export class AppComponent {
constructor(
private locationStrategyService: LocationStrategyService) {}
}