UNPKG

prevent-back

Version:

Prevent vistor go back to previous page

63 lines (49 loc) 1.52 kB
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); } export { preventBack as default, leave, stay };