prevent-back
Version:
Prevent vistor go back to previous page
75 lines (58 loc) • 2.08 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.preventBack = {}));
}(this, (function (exports) { 'use strict';
var _window = window,
document = _window.document,
history = _window.history;
var STATE_KEY = 'isPreventState';
var USER_INTERACTION_EVENTS = ['touchstart', 'click', 'keydown', 'keyup'];
var isPreventState = function isPreventState() {
var _history$state;
return (_history$state = history.state) === null || _history$state === void 0 ? void 0 : _history$state[STATE_KEY];
};
function setState() {
if (isPreventState()) {
return;
}
history.pushState({
[STATE_KEY]: true
}, document.title);
}
function bindUserInteractionEvent() {
var setStateByUserInteraction = function setStateByUserInteraction() {
setState();
if (isPreventState()) {
for (var _i2 = 0; _i2 < USER_INTERACTION_EVENTS.length; _i2++) {
var eventType = USER_INTERACTION_EVENTS[_i2];
window.removeEventListener(eventType, setStateByUserInteraction);
}
}
};
for (var _i4 = 0; _i4 < USER_INTERACTION_EVENTS.length; _i4++) {
var eventType = USER_INTERACTION_EVENTS[_i4];
window.addEventListener(eventType, setStateByUserInteraction);
}
}
var stay = setState;
var leave = function leave() {
history.back();
};
function bindStateChangeEvent(onAttemptToLeave) {
window.addEventListener('popstate', function () {
if (isPreventState()) {
return;
}
onAttemptToLeave(stay, leave);
});
}
function preventBack(onAttemptToLeave) {
bindUserInteractionEvent();
bindStateChangeEvent(onAttemptToLeave);
}
exports['default'] = preventBack;
exports.leave = leave;
exports.stay = stay;
Object.defineProperty(exports, '__esModule', { value: true });
})));