UNPKG

t-comm

Version:

专业、稳定、纯粹的工具库

39 lines (35 loc) 1.38 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); /** * 表单等数据变更时,提示用户是否确认离开当前页面 * @param checkDataCallback 可选,用于检查是否有未保存的数据变更,返回 true 则提示用户,返回 false 则不提示 * @returns 一个数组,第一个元素是移除事件监听的函数,第二个元素是事件处理函数 * * @example * ```ts * const [removeBeforeUnload] = initBeforeUnload(() => { * return form.isDirty; // 假设 form.isDirty 表示表单是否有未保存的更改 * }); * * // 在组件卸载或不再需要提示时调用 * removeBeforeUnload(); * ``` */ function initBeforeUnload(checkDataCallback) { var handler = function handler(event) { if (typeof checkDataCallback === 'function' && !checkDataCallback()) { return; } // Some browsers may not display the prompt if a custom message is set. // event.returnValue = 'You have unsaved changes. Are you sure you want to leave?'; // Cancel the event as stated by the standard. event.preventDefault(); // Chrome requires returnValue to be set. event.returnValue = ''; }; window.addEventListener('beforeunload', handler); return [function () { window.removeEventListener('beforeunload', handler); }, handler]; } exports.initBeforeUnload = initBeforeUnload;