Skip to content

Commit 2988176

Browse files
committed
🐛 修复脚本匹配、隐藏排序、首次打开浏览器加载脚本等问题 #317
1 parent 324e27a commit 2988176

11 files changed

Lines changed: 204 additions & 90 deletions

File tree

src/app/service/service_worker/index.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,18 @@ export default class ServiceWorkerManager {
106106
systemConfig.getCloudSync().then((config) => {
107107
synchronize.cloudSyncConfigChange(config);
108108
});
109+
110+
if (process.env.NODE_ENV === "production") {
111+
chrome.runtime.onInstalled.addListener((details) => {
112+
if (details.reason === "install") {
113+
chrome.tabs.create({ url: "https://docs.scriptcat.org/" });
114+
} else if (details.reason === "update") {
115+
chrome.tabs.create({
116+
url: `https://docs.scriptcat.org/docs/change/#${ExtVersion}`,
117+
});
118+
}
119+
});
120+
}
109121
}
110122

111123
checkUpdate() {

src/app/service/service_worker/resource.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,7 @@ export class ResourceService {
257257
return fetch(u.url)
258258
.then(async (resp) => {
259259
if (resp.status !== 200) {
260-
throw new Error(`resource response status not 200:${resp.status}`);
260+
throw new Error(`resource response status not 200: ${resp.status}`);
261261
}
262262
return {
263263
data: await resp.blob(),

src/app/service/service_worker/runtime.ts

Lines changed: 55 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { MessageQueue } from "@Packages/message/message_queue";
1+
import { MessageQueue, Unsubscribe } from "@Packages/message/message_queue";
22
import { ExtMessageSender, GetSender, Group, MessageSend } from "@Packages/message/server";
33
import {
44
Script,
@@ -15,20 +15,17 @@ import { subscribeScriptDelete, subscribeScriptEnable, subscribeScriptInstall }
1515
import { ScriptService } from "./script";
1616
import { runScript, stopScript } from "../offscreen/client";
1717
import { getRunAt } from "./utils";
18-
import { InfoNotification, isUserScriptsAvailable, randomString } from "@App/pkg/utils/utils";
18+
import { isUserScriptsAvailable, randomString } from "@App/pkg/utils/utils";
1919
import Cache from "@App/app/cache";
2020
import { dealPatternMatches, UrlMatch } from "@App/pkg/utils/match";
2121
import { ExtensionContentMessageSend } from "@Packages/message/extension_message";
2222
import { sendMessage } from "@Packages/message/client";
2323
import { compileInjectScript } from "../content/utils";
24-
import { PopupService } from "./popup";
25-
import Logger from "@App/app/logger/logger";
2624
import LoggerCore from "@App/app/logger/core";
2725
import PermissionVerify from "./permission_verify";
2826
import { SystemConfig } from "@App/pkg/config/config";
2927
import { ResourceService } from "./resource";
3028
import { LocalStorageDAO } from "@App/app/repo/localStorage";
31-
import i18n from "@App/locales/locales";
3229

3330
// 为了优化性能,存储到缓存时删除了code、value与resource
3431
export interface ScriptMatchInfo extends ScriptRunResouce {
@@ -52,6 +49,7 @@ export class RuntimeService {
5249
scriptMatchCache: Map<string, ScriptMatchInfo> | null | undefined;
5350

5451
isEnableDeveloperMode = false;
52+
isEnableUserscribe = true;
5553

5654
constructor(
5755
private systemConfig: SystemConfig,
@@ -102,8 +100,7 @@ export class RuntimeService {
102100
text: "!",
103101
});
104102
}
105-
// 读取inject.js注入页面
106-
this.registerInjectScript();
103+
107104
// 监听脚本开启
108105
subscribeScriptEnable(this.mq, async (data) => {
109106
const script = await this.scriptDAO.getAndCode(data.uuid);
@@ -114,6 +111,7 @@ export class RuntimeService {
114111
// 如果是后台脚本, 在offscreen中进行处理
115112
if (script.type === SCRIPT_TYPE_NORMAL) {
116113
// 加载页面脚本
114+
// 不管开没开启都要加载一次脚本信息
117115
await this.loadPageScript(script);
118116
if (!data.enable) {
119117
await this.unregistryPageScript(script.uuid);
@@ -136,6 +134,32 @@ export class RuntimeService {
136134
this.deleteScriptMatch(uuid);
137135
});
138136

137+
this.systemConfig.addListener("enable_script", (enable) => {
138+
this.isEnableUserscribe = enable;
139+
if (enable) {
140+
this.registerUserscripts();
141+
} else {
142+
this.unregisterUserscripts();
143+
}
144+
});
145+
// 检查是否开启
146+
this.isEnableUserscribe = await this.systemConfig.getEnableScript();
147+
if (this.isEnableUserscribe) {
148+
this.registerUserscripts();
149+
}
150+
}
151+
152+
unsubscribe: Unsubscribe[] = [];
153+
154+
// 取消脚本注册
155+
unregisterUserscripts() {
156+
chrome.userScripts.unregister();
157+
this.deleteMessageFlag();
158+
}
159+
160+
async registerUserscripts() {
161+
// 读取inject.js注入页面
162+
this.registerInjectScript();
139163
// 将开启的脚本发送一次enable消息
140164
const scriptDao = new ScriptDAO();
141165
const list = await scriptDao.all();
@@ -164,6 +188,10 @@ export class RuntimeService {
164188
});
165189
}
166190

191+
deleteMessageFlag() {
192+
return Cache.getInstance().del("scriptInjectMessageFlag");
193+
}
194+
167195
getMessageFlag() {
168196
return Cache.getInstance().get("scriptInjectMessageFlag");
169197
}
@@ -241,7 +269,7 @@ export class RuntimeService {
241269
return undefined;
242270
}
243271
// 如果是iframe,判断是否允许在iframe里运行
244-
if (chromeSender.frameId !== undefined) {
272+
if (chromeSender.frameId) {
245273
if (scriptRes.metadata.noframes) {
246274
return undefined;
247275
}
@@ -420,8 +448,11 @@ export class RuntimeService {
420448
if (!this.scriptMatchCache) {
421449
await this.loadScriptMatchInfo();
422450
}
423-
this.scriptMatchCache!.get(uuid)!.status = status;
424-
this.saveScriptMatchInfo();
451+
const script = await this.scriptMatchCache!.get(uuid);
452+
if (script) {
453+
script.status = status;
454+
this.saveScriptMatchInfo();
455+
}
425456
}
426457

427458
async deleteScriptMatch(uuid: string) {
@@ -487,8 +518,10 @@ export class RuntimeService {
487518
this.addScriptMatch(scriptMatchInfo);
488519

489520
// 如果脚本开启, 则注册脚本
490-
if (this.isEnableDeveloperMode && script.status === SCRIPT_STATUS_ENABLE) {
491-
if (!scriptRes.metadata["noframes"]) {
521+
if (this.isEnableDeveloperMode && this.isEnableUserscribe && script.status === SCRIPT_STATUS_ENABLE) {
522+
if (scriptRes.metadata["noframes"]) {
523+
registerScript.allFrames = false;
524+
} else {
492525
registerScript.allFrames = true;
493526
}
494527
if (scriptRes.metadata["run-at"]) {
@@ -524,19 +557,17 @@ export class RuntimeService {
524557
}
525558

526559
async unregistryPageScript(uuid: string) {
527-
if (!this.isEnableDeveloperMode || !(await Cache.getInstance().get("registryScript:" + uuid))) {
560+
if (
561+
!this.isEnableDeveloperMode ||
562+
!this.isEnableUserscribe ||
563+
!(await Cache.getInstance().get("registryScript:" + uuid))
564+
) {
528565
return;
529566
}
530-
chrome.userScripts.unregister(
531-
{
532-
ids: [uuid],
533-
},
534-
() => {
535-
// 删除缓存
536-
Cache.getInstance().del("registryScript:" + uuid);
537-
// 修改脚本状态为disable
538-
this.updateScriptStatus(uuid, SCRIPT_STATUS_DISABLE);
539-
}
540-
);
567+
// 删除缓存
568+
Cache.getInstance().del("registryScript:" + uuid);
569+
// 修改脚本状态为disable
570+
this.updateScriptStatus(uuid, SCRIPT_STATUS_DISABLE);
571+
chrome.userScripts.unregister({ ids: [uuid] });
541572
}
542573
}

src/locales/zh-CN/translation.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -369,5 +369,7 @@
369369
"export_success": "导出成功",
370370
"get_backup_dir_url_failed": "获取备份目录地址失败",
371371
"get_backup_files_failed": "获取备份文件失败",
372-
"develop_mode_guide": "检测到当前未开启开发者模式,您的脚本无法正常使用,<a href=\"https://docs.scriptcat.org/docs/use/open-dev/\" target=\"black\" style=\"color: var(--color-text-1)\">👉点我了解如何开启</a>"
372+
"develop_mode_guide": "检测到当前未开启开发者模式,您的脚本无法正常使用,<a href=\"https://docs.scriptcat.org/docs/use/open-dev/\" target=\"black\" style=\"color: var(--color-text-1)\">👉点我了解如何开启</a>",
373+
"enable_script_failed": "脚本开启失败",
374+
"disable_script_failed": "脚本关闭失败"
373375
}

src/pages/options/routes/ScriptList.tsx

Lines changed: 44 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,8 @@ import {
8181
requestStopScript,
8282
requestRunScript,
8383
scriptClient,
84+
enableLoading,
85+
updateEnableStatus,
8486
} from "@App/pages/store/features/script";
8587
import { message, systemConfig } from "@App/pages/store/global";
8688
import { SynchronizeClient, ValueClient } from "@App/app/service/service_worker/client";
@@ -615,6 +617,7 @@ function ScriptList() {
615617
const dealColumns: ColumnProps[] = [];
616618

617619
newColumns.forEach((item) => {
620+
console.log(newColumns);
618621
switch (item.width) {
619622
case -1:
620623
break;
@@ -625,37 +628,39 @@ function ScriptList() {
625628
});
626629

627630
const sortIndex = dealColumns.findIndex((item) => item.key === "sort");
631+
let SortableItem;
632+
if (sortIndex !== -1) {
633+
SortableItem = (props: any) => {
634+
const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: props!.record.uuid });
628635

629-
const SortableItem = (props: any) => {
630-
const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: props!.record.uuid });
636+
const style = {
637+
transform: CSS.Transform.toString(transform),
638+
transition,
639+
};
631640

632-
const style = {
633-
transform: CSS.Transform.toString(transform),
634-
transition,
635-
};
636-
637-
// 替换排序列,使其可以拖拽
638-
props.children[sortIndex + 1] = (
639-
<td
640-
className="arco-table-td"
641-
style={{
642-
textAlign: "center",
643-
}}
644-
key="drag"
645-
>
646-
<div className="arco-table-cell">
647-
<IconMenu
648-
style={{
649-
cursor: "move",
650-
}}
651-
{...listeners}
652-
/>
653-
</div>
654-
</td>
655-
);
641+
// 替换排序列,使其可以拖拽
642+
props.children[sortIndex + 1] = (
643+
<td
644+
className="arco-table-td"
645+
style={{
646+
textAlign: "center",
647+
}}
648+
key="drag"
649+
>
650+
<div className="arco-table-cell">
651+
<IconMenu
652+
style={{
653+
cursor: "move",
654+
}}
655+
{...listeners}
656+
/>
657+
</div>
658+
</td>
659+
);
656660

657-
return <tr ref={setNodeRef} style={style} {...attributes} {...props} />;
658-
};
661+
return <tr ref={setNodeRef} style={style} {...attributes} {...props} />;
662+
};
663+
}
659664

660665
const components: ComponentsProps = {
661666
table: React.forwardRef(SortableWrapper),
@@ -703,19 +708,23 @@ function ScriptList() {
703708
type="primary"
704709
size="mini"
705710
onClick={() => {
706-
const uuids: string[] = [];
711+
const enableAction = (enable: boolean) => {
712+
const uuids = select.map((item) => item.uuid);
713+
dispatch(enableLoading({ uuids: uuids, loading: true }));
714+
Promise.allSettled(uuids.map((uuid) => scriptClient.enable(uuid, enable))).finally(() => {
715+
dispatch(updateEnableStatus({ uuids: uuids, enable: enable }));
716+
dispatch(enableLoading({ uuids: uuids, loading: false }));
717+
});
718+
};
707719
switch (action) {
708720
case "enable":
709-
select.forEach((item) => {
710-
dispatch(requestEnableScript({ uuid: item.uuid, enable: true }));
711-
});
721+
enableAction(true);
712722
break;
713723
case "disable":
714-
select.forEach((item) => {
715-
dispatch(requestEnableScript({ uuid: item.uuid, enable: false }));
716-
});
724+
enableAction(false);
717725
break;
718726
case "export":
727+
const uuids: string[] = [];
719728
select.forEach((item) => {
720729
uuids.push(item.uuid);
721730
});

src/pages/options/routes/Tools.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,15 @@ function Tools() {
3030
useEffect(() => {
3131
// 获取配置
3232
const loadConfig = async () => {
33-
const [backup, vscodeUrl] = await Promise.all([
33+
const [backup, vscodeUrl, vscodeReconnect] = await Promise.all([
3434
systemConfig.getBackup(),
3535
systemConfig.getVscodeUrl(),
3636
systemConfig.getVscodeReconnect(),
3737
]);
3838
setFilesystemType(backup.filesystem);
3939
setFilesystemParam(backup.params[backup.filesystem] || {});
4040
setVscodeUrl(vscodeUrl);
41-
setVscodeReconnect(systemConfig.vscodeReconnect);
41+
setVscodeReconnect(vscodeReconnect);
4242
};
4343
loadConfig();
4444
}, []);

src/pages/popup/App.tsx

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import {
1111
IconSearch,
1212
} from "@arco-design/web-react/icon";
1313
import React, { useEffect, useState } from "react";
14-
import { RiMessage2Line } from "react-icons/ri";
14+
import { RiMessage2Line, RiZzzFill } from "react-icons/ri";
1515
import semver from "semver";
1616
import { useTranslation } from "react-i18next";
1717
import ScriptMenuList from "../components/ScriptMenuList";
@@ -38,7 +38,7 @@ function App() {
3838
isRead: false,
3939
});
4040
const [currentUrl, setCurrentUrl] = useState("");
41-
const [isEnableScript, setIsEnableScript] = useState(localStorage.enable_script !== "false");
41+
const [isEnableScript, setIsEnableScript] = useState(true);
4242
const { t } = useTranslation();
4343

4444
let url: URL | undefined;
@@ -49,9 +49,15 @@ function App() {
4949
}
5050

5151
useEffect(() => {
52-
systemConfig.getCheckUpdate().then((res) => {
53-
setCheckUpdate(res);
54-
});
52+
const loadConfig = async () => {
53+
const [isEnableScript, checkUpdate] = await Promise.all([
54+
systemConfig.getEnableScript(),
55+
systemConfig.getCheckUpdate(),
56+
]);
57+
setIsEnableScript(isEnableScript);
58+
setCheckUpdate(checkUpdate);
59+
};
60+
loadConfig();
5561
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
5662
if (!tabs.length) {
5763
return;
@@ -95,9 +101,9 @@ function App() {
95101
onChange={(val) => {
96102
setIsEnableScript(val);
97103
if (val) {
98-
localStorage.enable_script = "true";
104+
systemConfig.setEnableScript(true);
99105
} else {
100-
localStorage.enable_script = "false";
106+
systemConfig.setEnableScript(false);
101107
}
102108
}}
103109
/>

0 commit comments

Comments
 (0)