Skip to content

Commit

Permalink
feat(core): 添加优先级选项,排序特定脚本的执行速度
Browse files Browse the repository at this point in the history
  • Loading branch information
enncy committed Oct 25, 2023
1 parent 7f7a0ac commit 049234c
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 9 deletions.
8 changes: 7 additions & 1 deletion packages/core/src/interfaces/script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ export interface ScriptOptions<C extends Record<string, Config>> {
configs?: ScriptConfigsProvider<C>;
/** 不显示脚本页 */
hideInPanel?: boolean;
/** 运行优先级 */
priority?: number;
}

export type ScriptConfigs = {
Expand Down Expand Up @@ -103,6 +105,8 @@ export class Script<
methods: M = Object.create({});
/** 自定义事件触发器,避免使用 script.emit , script.on 导致与原有的事件冲突,使用 script.event.emit 和 script.event.on */
event: EventEmitter = new EventEmitter();
/** 运行优先级,默认0 */
priority: number;

get configs() {
if (!this._resolvedConfigs) {
Expand All @@ -128,7 +132,8 @@ export class Script<
onbeforeunload,
onrender,
onhistorychange,
methods
methods,
priority
}: ScriptOptions<C> & {
onstart?: (this: Script<C, M>, ...args: any) => any;
onactive?: (this: Script<C, M>, ...args: any) => any;
Expand All @@ -152,6 +157,7 @@ export class Script<
this.onrender = this.errorHandler(onrender);
this.onhistorychange = this.errorHandler(onhistorychange);
this.methods = methods?.bind(this)() || Object.create({});
this.priority = priority ?? 0;

if (this.methods) {
for (const key in methods) {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/utils/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export async function start(startConfig: StartConfig) {
return p;
});

const scripts = $.getMatchedScripts(startConfig.projects, [location.href]);
const scripts = $.getMatchedScripts(startConfig.projects, [location.href]).sort((a, b) => b.priority - a.priority);

/** 执行脚本 */
scripts.forEach((script) => {
Expand Down
20 changes: 13 additions & 7 deletions packages/scripts/src/projects/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -920,15 +920,21 @@ export const CommonProject = Project.create({
name: '禁止弹窗',
url: [['所有页面', /.*/]],
hideInPanel: true,
priority: 1,
onstart() {
function disableDialog(msg: string) {
$modal('alert', {
profile: '弹窗来自:' + location.origin,
content: msg
});
}

try {
$gm.unsafeWindow.alert = (msg) => {
$modal('alert', {
profile: '弹窗来自:' + location.origin,
content: msg
});
};
} catch (e) {}
$gm.unsafeWindow.alert = disableDialog;
window.alert = disableDialog;
} catch (e) {
console.error(e);
}
}
}),
apps: new Script({
Expand Down

0 comments on commit 049234c

Please sign in to comment.