Skip to content

Commit 7b81677

Browse files
committed
🐛 修复后台脚本无法处理blob的问题 #34
1 parent a706827 commit 7b81677

7 files changed

Lines changed: 79 additions & 41 deletions

File tree

src/apps/grant/background.ts

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -530,7 +530,6 @@ export class BackgroundGrant {
530530
@BackgroundGrant.GMFunction({
531531
confirm: (grant: Grant, script: Script) => {
532532
return new Promise(resolve => {
533-
console.log(grant, script);
534533
const config = <GM_Types.XHRDetails>grant.params[0];
535534
const url = new URL(config.url);
536535
if (script.metadata['connect']) {
@@ -664,6 +663,30 @@ export class BackgroundGrant {
664663
});
665664
}
666665

666+
// CAT_fetchBlob与CAT_createBlobUrl 沙盒中才有效,前端的在src/content.ts中处理
667+
@BackgroundGrant.GMFunction({
668+
default: true
669+
})
670+
protected CAT_fetchBlob(grant: Grant): Promise<any> {
671+
return new Promise(resolve => {
672+
const handler = async () => {
673+
const resp=await (await fetch(<string>grant.params[0])).blob();
674+
console.log('fetch',resp);
675+
resolve(resp);
676+
}
677+
void handler();
678+
});
679+
}
680+
681+
@BackgroundGrant.GMFunction({
682+
default: true
683+
})
684+
protected CAT_createBlobUrl(grant: Grant): Promise<any> {
685+
return new Promise(resolve => {
686+
resolve(URL.createObjectURL(<Blob>grant.params[0]));
687+
});
688+
}
689+
667690
@BackgroundGrant.GMFunction({
668691
confirm: (grant: Grant, script: Script) => {
669692
return new Promise((resolve, reject) => {

src/apps/grant/frontend.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ export class FrontendGrant implements ScriptContext {
147147
});
148148
}
149149

150-
@FrontendGrant.GMFunction({ depend: ['CAT_fetchBlob', 'CAT_createBlobUrl','CAT_abortXhr'] })
150+
@FrontendGrant.GMFunction({ depend: ['CAT_fetchBlob', 'CAT_createBlobUrl', 'CAT_abortXhr'] })
151151
public GM_xmlhttpRequest(details: GM_Types.XHRDetails): GM_Types.AbortHandle<void> {
152152
let abort = () => { return };
153153
const handler = async () => {
@@ -262,7 +262,6 @@ export class FrontendGrant implements ScriptContext {
262262
details.onabort && details.onabort();
263263
break;
264264
case 'requestId':
265-
console.log(data.data);
266265
abort = () => {
267266
this.CAT_abortXhr(<number>data.data);
268267
}

src/apps/msg-center/msg-center.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { compileScript } from "@App/pkg/sandbox/compile";
12

23
export type ListenCallback = (msg: any, port: chrome.runtime.Port) => Promise<any> | any;
34

src/apps/script/manager.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -856,7 +856,6 @@ export class ScriptManager extends Manager {
856856
}
857857
}
858858
await this.scriptModel.save(script);
859-
console.log(script.metadata['connect']);
860859
AppEvent.trigger(ScriptStatusChange, script);
861860
return resolve(true);
862861
});

src/content.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ chrome.runtime.sendMessage('runScript', (event: unknown) => {
1919
browserMsg.send(msg.flag, msg);
2020
break;
2121
case 'CAT_createBlobUrl':
22-
msg.data = URL.createObjectURL(msg.params[0]);
22+
msg.data = URL.createObjectURL(<Blob>msg.params[0]);
2323
browserMsg.send(msg.flag, msg);
2424
break;
2525
default:

src/pkg/sandbox/compile.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@ export function compileScriptCode(script: ScriptCache): string {
1818
}
1919

2020
// 编译成脚本方法
21-
export function compileScript(script: ScriptCache): any {
22-
return new Function('context', script.code);
21+
export function compileScript(script: ScriptCache): (param: AnyMap) => void {
22+
return <(param: AnyMap) => void>new Function('context', script.code);
2323
}
2424

2525
// 设置api依赖

src/sandbox.ts

Lines changed: 50 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { CronJob } from 'cron';
2-
import { buildThis } from '@App/pkg/sandbox/sandbox';
2+
import { buildThis } from './pkg/sandbox/sandbox';
33
import { SandboxContext } from './apps/grant/frontend';
44
import { SendLogger } from './pkg/utils/utils';
55
import { App, ENV_FRONTEND, InitApp } from './apps/app';
@@ -23,46 +23,50 @@ type ExecType = 'run' | 'crontab' | 'retry' | 'debug';
2323

2424
async function execScript(
2525
script: Script,
26-
func: Function,
26+
func: (param: AnyMap) => any,
2727
context: SandboxContext,
2828
type: ExecType = 'run',
2929
): Promise<boolean> {
30-
return new Promise(async (resolve, reject) => {
30+
return new Promise((resolve, reject) => {
3131
//使用SandboxContext接管postRequest
3232
script.delayruntime = 0;
3333
context.CAT_setRunError('', 0);
3434
script.lastruntime = new Date().getTime();
3535
context.CAT_setLastRuntime(script.lastruntime);
36-
SendLogger(LOGGER_LEVEL_INFO, type, 'exec script id: ' + script.id, script.name, script.id);
36+
SendLogger(LOGGER_LEVEL_INFO, type, 'exec script id: ' + script.id.toString(), script.name, script.id);
3737
let execRet;
3838
try {
3939
execRet = func(buildThis(window, context));
4040
} catch (error: any) {
41-
let msg = 'exec script id: ' + script.id + ' time: ' + (new Date().getTime() - (script.lastruntime || 0)).toString() + 'ms'
42-
if (error) {
41+
let msg = 'exec script id: ' + script.id.toString() + ' time: ' + (new Date().getTime() - (script.lastruntime || 0)).toString() + 'ms'
42+
let errMsg = '';
43+
if (typeof error === 'string') {
4344
msg += ' error: ' + error;
45+
errMsg = error;
46+
} else {
47+
errMsg = 'unknow error';
4448
}
4549
SendLogger(LOGGER_LEVEL_ERROR, type, msg, script.name, script.id);
4650
script.delayruntime = 0;
47-
context.CAT_setRunError(error, script.delayruntime);
51+
context.CAT_setRunError(errMsg, script.delayruntime);
4852
reject(error);
4953
return
5054
}
5155
if (execRet instanceof Promise) {
5256
execRet
5357
.then((result: any) => {
54-
let msg = 'exec script id: ' + script.id + ' time: ' + (new Date().getTime() - (script.lastruntime || 0)).toString() + 'ms'
55-
if (result) {
58+
let msg = 'exec script id: ' + script.id.toString() + ' time: ' + (new Date().getTime() - (script.lastruntime || 0)).toString() + 'ms'
59+
if (typeof result == 'string') {
5660
msg += ' result: ' + result;
5761
}
5862
SendLogger(LOGGER_LEVEL_INFO, type, msg, script.name, script.id);
5963
context.CAT_runComplete();
60-
resolve(result);
64+
resolve(true);
6165
})
6266
.catch((error: string, delayrun = 0) => {
63-
let msg = 'exec script id: ' + script.id + ' time: ' + (new Date().getTime() - (script.lastruntime || 0)).toString() + 'ms'
67+
let msg = 'exec script id: ' + script.id.toString() + ' time: ' + (new Date().getTime() - (script.lastruntime || 0)).toString() + 'ms'
6468
if (error) {
65-
msg += ' error: ' + error + (delayrun ? ' delayrun: ' + delayrun : '')
69+
msg += ' error: ' + error + (delayrun ? ' delayrun: ' + delayrun.toString() : '')
6670
}
6771
SendLogger(LOGGER_LEVEL_ERROR, type, msg, script.name, script.id);
6872
if (delayrun > 0) {
@@ -74,14 +78,26 @@ async function execScript(
7478
reject(error);
7579
});
7680
} else {
81+
let result = ' result:';
82+
switch (typeof execRet) {
83+
case 'string':
84+
result += execRet;
85+
break;
86+
case 'undefined':
87+
result = '';
88+
break;
89+
default:
90+
result += JSON.stringify(execRet);
91+
break;
92+
}
7793
SendLogger(
7894
LOGGER_LEVEL_INFO,
7995
type,
8096
'exec script id: ' +
81-
script.id +
97+
script.id.toString() +
8298
' time: ' +
8399
(new Date().getTime() - (script.lastruntime || 0)).toString() +
84-
'ms' + (execRet ? ' result:' + execRet : ''),
100+
'ms' + result,
85101
script.name, script.id
86102
);
87103
context.CAT_runComplete();
@@ -95,16 +111,16 @@ function start(script: ScriptCache): any {
95111
return runCrontab(script);
96112
} else if (script.metadata['background']) {
97113
const context = createSandboxContext(script);
98-
App.Cache.set('script:' + script.id, context);
99-
execScript(script, compileScript(script), context, 'run');
100-
return top!.postMessage({ action: 'start', data: '' }, '*');
114+
void App.Cache.set('script:' + script.id.toString(), context);
115+
void execScript(script, compileScript(script), context, 'run');
116+
return top?.postMessage({ action: 'start', data: '' }, '*');
101117
}
102118
}
103119

104120
function runCrontab(script: ScriptCache) {
105121
const crontab = script.metadata['crontab'];
106122
const context = createSandboxContext(script);
107-
App.Cache.set('script:' + script.id, context);
123+
void App.Cache.set('script:' + script.id.toString(), context);
108124
const func = compileScript(script);
109125

110126
const list = new Array<CronJob>();
@@ -132,13 +148,13 @@ function runCrontab(script: ScriptCache) {
132148
() => {
133149
if (oncePos) {
134150
if (!script.lastruntime) {
135-
execScript(script, func, context, 'crontab');
151+
void execScript(script, func, context, 'crontab');
136152
return;
137153
}
138154
const now = new Date();
139155
if (script.delayruntime && script.delayruntime < now.getTime()) {
140156
//TODO:使用单独的计时器执行
141-
execScript(script, func, context, 'retry');
157+
void execScript(script, func, context, 'retry');
142158
return;
143159
}
144160
if (script.lastruntime > now.getTime()) {
@@ -167,10 +183,10 @@ function runCrontab(script: ScriptCache) {
167183
default:
168184
}
169185
if (flag) {
170-
execScript(script, func, context, 'crontab');
186+
void execScript(script, func, context, 'crontab');
171187
}
172188
} else {
173-
execScript(script, func, context, 'crontab');
189+
void execScript(script, func, context, 'crontab');
174190
}
175191
},
176192
null,
@@ -179,44 +195,44 @@ function runCrontab(script: ScriptCache) {
179195
list.push(cron);
180196
});
181197
cronjobMap.set(script.id, list);
182-
return top!.postMessage({ action: 'start', data: '' }, '*');
198+
return top?.postMessage({ action: 'start', data: '' }, '*');
183199
}
184200

185-
async function exec(script: ScriptCache, isdebug: boolean) {
201+
function exec(script: ScriptCache, isdebug: boolean) {
186202
const context = createSandboxContext(script);
187-
App.Cache.set('script:' + (isdebug ? 'debug:' : '') + script.id, context);
203+
void App.Cache.set('script:' + (isdebug ? 'debug:' : '') + script.id.toString(), context);
188204
execScript(script, compileScript(script), context, isdebug ? 'debug' : 'run').then(result => {
189-
top!.postMessage({ action: 'exec respond', data: 'success', result: result }, '*');
205+
top?.postMessage({ action: 'exec respond', data: 'success', result: result }, '*');
190206
}).catch(error => {
191-
top!.postMessage({ action: 'exec respond', data: 'error', error: error }, '*');
207+
top?.postMessage({ action: 'exec respond', data: 'error', error: error }, '*');
192208
});
193-
return top!.postMessage({ action: 'exec', data: '' }, '*');
209+
return top?.postMessage({ action: 'exec', data: '' }, '*');
194210
}
195211

196212
async function disable(script: Script) {
197213
const context = <SandboxContext>(
198-
await App.Cache.get('script:' + script.id)
214+
await App.Cache.get('script:' + script.id.toString())
199215
);
200216
if (context) {
201217
context.destruct();
202218
}
203219
if (script.type != SCRIPT_TYPE_CRONTAB) {
204-
return top!.postMessage({ action: 'disable' }, '*');
220+
return top?.postMessage({ action: 'disable' }, '*');
205221
}
206222
const list = cronjobMap.get(script.id);
207223
if (!list) {
208-
return top!.postMessage({ action: 'disable' }, '*');
224+
return top?.postMessage({ action: 'disable' }, '*');
209225
}
210226
list.forEach((val) => {
211227
val.stop();
212228
});
213229
cronjobMap.delete(script.id);
214-
return top!.postMessage({ action: 'disable' }, '*');
230+
return top?.postMessage({ action: 'disable' }, '*');
215231
}
216232

217233
async function stop(script: Script, isdebug: boolean) {
218234
const context = <SandboxContext>(
219-
await App.Cache.get('script:' + (isdebug ? 'debug:' : '') + script.id)
235+
await App.Cache.get('script:' + (isdebug ? 'debug:' : '') + script.id.toString())
220236
);
221237
if (context) {
222238
if (script.type == SCRIPT_TYPE_CRONTAB) {
@@ -225,7 +241,7 @@ async function stop(script: Script, isdebug: boolean) {
225241
context.destruct();
226242
}
227243
}
228-
return top!.postMessage({ action: 'stop' }, '*');
244+
return top?.postMessage({ action: 'stop' }, '*');
229245
}
230246

231247
function getWeek(date: Date) {

0 commit comments

Comments
 (0)