storywright/pageinit.back

82 строки
2.4 KiB
Plaintext

//Just for backup to refer later
this.page.addInitScript(`{
const _promiseConstructor = window.Promise.constructor;
const _timeoutIds = new Set();
const _setTimeout = window.setTimeout;
const _clearTimeout = window.clearTimeout;
new MutationObserver(() => {
window.__pwBusy__("dom++");
requestAnimationFrame(() => { window.__pwBusy__("dom--"); });
}).observe(document, { attributes: true, childList: true, subtree: true });
// Patch Promise constructor
window.Promise.constructor = async (resolve, reject) => {
window.__pwBusy__("promises++");
const res = resolve && (async () => {
let val;
try {
val = await resolve();
} catch(err) {
throw err;
} finally {
window.__pwBusy__("promises--");
}
return val;
});
const rej = reject && (async () => {
let val;
try {
val = await reject();
} catch(err) {
throw err;
} finally {
window.__pwBusy__("promises--");
}
return val;
});
return _promiseConstructor.call(this, res, rej);
};
// Path window.clearTimeout
window.clearTimeout = (id) => {
_clearTimeout(id);
if (_timeoutIds.has(id)) {
_timeoutIds.delete(id);
window.__pwBusy__("timeouts--");
}
};
// Patch window.setTimeout in the near future
window.setTimeout = (...args) => {
const ms = args[1];
const isInNearFuture = ms < 1000 * 5;
if (isInNearFuture) {
window.__pwBusy__("timeouts++");
const fn = args[0];
if (typeof(fn) === "function") {
args[0] = () => {
try {
fn();
} catch(err) {
} finally {
window.__pwBusy__("timeouts--");
}
};
} else {
args[0] = "try{" + args[0] + "; }catch(err){};window.__pwBusy__('timeouts--');";
}
}
const timeoutId = _setTimeout.apply(this, args);
if (isInNearFuture) {
_timeoutIds.add(timeoutId);
}
return timeoutId;
};
}`);