Skip to content

Commit

Permalink
fix(core): 优化 start 主函数,防止脚本重新执行
Browse files Browse the repository at this point in the history
  • Loading branch information
enncy committed Jan 1, 2023
1 parent a22ec8b commit bef652d
Showing 1 changed file with 23 additions and 5 deletions.
28 changes: 23 additions & 5 deletions packages/core/src/utils/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,23 @@ export function start(cfg: StartConfig) {
script.onstart?.(cfg);
});

/** 防止 onactive 执行两次 */
let active = false;

/** 存在一开始就是 active 的情况 */
if (document.readyState === 'interactive') {
active = true;
scripts.forEach((script) => {
script.onactive?.(cfg);
});
}

document.addEventListener('readystatechange', () => {
if (document.readyState === 'interactive') {
if (
document.readyState === 'interactive' &&
/** 防止执行两次 */
active === false
) {
scripts.forEach((script) => {
script.onactive?.(cfg);
});
Expand All @@ -60,9 +69,18 @@ export function start(cfg: StartConfig) {
}
});

window.onbeforeunload = () => {
scripts.forEach((script) => {
script.onbeforeunload?.(cfg);
});
window.onbeforeunload = (e) => {
let prevent;
for (const script of scripts) {
if (script.onbeforeunload?.(cfg)) {
prevent = true;
}
}

if (prevent) {
e.preventDefault();
e.returnValue = true;
return true;
}
};
}

0 comments on commit bef652d

Please sign in to comment.