阻止浏览器回退、刷新、关闭页面事件(ember / vue 框架)

17 篇文章 0 订阅
2 篇文章 0 订阅

以ember框架为例:

封装的service:

import Service from '@ember/service'
import { inject as service } from "@ember/service"
import fetch from 'fetch'
import { tracked } from '@glimmer/tracking'
import { action } from '@ember/object'


export default class BrowserEventsServiceService extends Service {
	@tracked param
	@tracked routeName
	@service router

	// 注册浏览器监听事件
	registerListener(route) {
		let that = this
		$(function(){
			that.param = this.location.href.split('?')[1]
			that.routeName = `/${route}?`
			//回退
			if (window.history && window.history.pushState) {
				history.pushState(null, null, document.URL);
				
				window.addEventListener("popstate", that.popstateFun, false);
			}
			//关闭&刷新(页面有变动或距上次刷新间隔超过5s时生效)
			window.onbeforeunload=function(e){
				return false
			}
			//文档加载完成后立即触发
			window.onload = function(){
				// 刷新回到指定页面
                that.router.transitionTo( `${that.routeName}${that.param}` )
			}	
		});
	}

	@action
	popstateFun() {
		let that = this
		let sel = confirm("您还没有保存更改,确认返回吗?")
		if(sel) {
			window.removeEventListener("popstate", that.popstateFun);
			that.router.transitionTo( `${that.routeName}${that.param}` )
		} else {
			history.pushState(null, null, document.URL);
		}
	}
	//清除浏览器监听事件
	clearListener() {
		window.onbeforeunload = undefined
		window.removeEventListener("popstate",this.popstateFun)
	}
}

用法:

    @service browserEventsService;
	
	beforeModel() {
		// 1. 清除所有页面监听事件,防止重复调用
		this.browserEventsService.clearListener()
		// 2. 注册监听事件,参数为要跳转页面的router
		this.browserEventsService.registerListener('flow')
    }

vue用法同上。

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值