Compare commits

...

10 Commits

Author SHA1 Message Date
ec28795dbb 脚本开启总开关 2025-04-29 14:14:10 +08:00
44041f4735 打开文档页面/更新日志 2025-04-29 11:57:16 +08:00
ffabe268b1 修复匹配问题与优化批量开启速度 2025-04-29 11:53:59 +08:00
ddd3219bae 更大范围的脚本匹配 2025-04-29 11:28:01 +08:00
14baa176d9 🐛 修复隐藏排序问题 #317 2025-04-29 10:42:29 +08:00
3c1e30182f 优化打包体积 2025-04-29 10:25:15 +08:00
1aaf1bbd4a 修复首次打开浏览器加载脚本的问题 2025-04-28 23:24:11 +08:00
8a216933ca vscode reconnect 2025-04-28 18:04:20 +08:00
51fe2a89e1 开启开发者模式引导 2025-04-28 15:20:26 +08:00
a26f1c5014 优化细节 2025-04-27 18:02:57 +08:00
22 changed files with 679 additions and 376 deletions

View File

@ -1,6 +1,6 @@
{ {
"name": "scriptcat", "name": "scriptcat",
"version": "0.17.0-alpha.2", "version": "0.17.0-alpha.4",
"description": "脚本猫,一个可以执行用户脚本的浏览器扩展,万物皆可脚本化,让你的浏览器可以做更多的事情!", "description": "脚本猫,一个可以执行用户脚本的浏览器扩展,万物皆可脚本化,让你的浏览器可以做更多的事情!",
"author": "CodFrm", "author": "CodFrm",
"license": "GPLv3", "license": "GPLv3",

View File

@ -208,6 +208,16 @@ export default defineConfig({
minimizerOptions: { targets }, minimizerOptions: { targets },
}), }),
], ],
splitChunks: {
chunks: (chunk) => {
// 排除这些文件,不进行分离
return !["editor.worker", "ts.worker", "linter.worker", "service_worker", "content", "inject"].includes(
chunk.name || ""
);
},
minSize: 307200,
maxSize: 4194304,
},
}, },
experiments: { experiments: {
css: true, css: true,

View File

@ -113,7 +113,6 @@ function renameField() {
if (subscribe.length) { if (subscribe.length) {
await Promise.all( await Promise.all(
subscribe.map((s: Subscribe) => { subscribe.map((s: Subscribe) => {
console.log("1234", s);
const { url, name, code, author, scripts, metadata, status, createtime, updatetime, checktime } = s; const { url, name, code, author, scripts, metadata, status, createtime, updatetime, checktime } = s;
return subscribeDAO.save({ return subscribeDAO.save({
url, url,

View File

@ -23,6 +23,7 @@ export default class ContentRuntime {
// 转发给inject // 转发给inject
return sendMessage(this.msg, "inject/runtime/valueUpdate", data); return sendMessage(this.msg, "inject/runtime/valueUpdate", data);
}); });
forwardMessage("serviceWorker", "script/isInstalled", this.server, this.extSend);
forwardMessage( forwardMessage(
"serviceWorker", "serviceWorker",
"runtime/gmApi", "runtime/gmApi",

View File

@ -4,6 +4,8 @@ import ExecScript, { ValueUpdateData } from "./exec_script";
import { addStyle, ScriptFunc } from "./utils"; import { addStyle, ScriptFunc } from "./utils";
import { getStorageName } from "@App/pkg/utils/utils"; import { getStorageName } from "@App/pkg/utils/utils";
import { EmitEventRequest } from "../service_worker/runtime"; import { EmitEventRequest } from "../service_worker/runtime";
import { ExternalWhitelist } from "@App/app/const";
import { sendMessage } from "@Packages/message/client";
export class InjectRuntime { export class InjectRuntime {
execList: ExecScript[] = []; execList: ExecScript[] = [];
@ -44,6 +46,40 @@ export class InjectRuntime {
val.valueUpdate(data); val.valueUpdate(data);
}); });
}); });
// 注入允许外部调用
this.externalMessage();
}
externalMessage() {
// 对外接口白名单
let msg = this.msg;
for (let i = 0; i < ExternalWhitelist.length; i += 1) {
if (window.location.host.endsWith(ExternalWhitelist[i])) {
// 注入
(<{ external: any }>(<unknown>window)).external = window.external || {};
(<
{
external: {
Scriptcat: {
isInstalled: (name: string, namespace: string, callback: any) => void;
};
};
}
>(<unknown>window)).external.Scriptcat = {
async isInstalled(name: string, namespace: string, callback: any) {
const resp = await sendMessage(msg, "content/script/isInstalled", {
name,
namespace,
});
callback(resp);
},
};
(<{ external: { Tampermonkey: any } }>(<unknown>window)).external.Tampermonkey = (<
{ external: { Scriptcat: any } }
>(<unknown>window)).external.Scriptcat;
break;
}
}
} }
execScript(script: ScriptRunResouce, scriptFunc: ScriptFunc) { execScript(script: ScriptRunResouce, scriptFunc: ScriptFunc) {

View File

@ -9,6 +9,8 @@ import { PopupService } from "./popup";
import { SystemConfig } from "@App/pkg/config/config"; import { SystemConfig } from "@App/pkg/config/config";
import { SynchronizeService } from "./synchronize"; import { SynchronizeService } from "./synchronize";
import { SubscribeService } from "./subscribe"; import { SubscribeService } from "./subscribe";
import { ExtServer, ExtVersion } from "@App/app/const";
import { systemConfig } from "@App/pages/store/global";
export type InstallSource = "user" | "system" | "sync" | "subscribe" | "vscode"; export type InstallSource = "user" | "system" | "sync" | "subscribe" | "vscode";
@ -78,8 +80,17 @@ export default class ServiceWorkerManager {
case "checkSubscribeUpdate": case "checkSubscribeUpdate":
subscribe.checkSubscribeUpdate(); subscribe.checkSubscribeUpdate();
break; break;
case "checkUpdate":
// 检查扩展更新
this.checkUpdate();
break;
} }
}); });
// 8小时检查一次扩展更新
chrome.alarms.create("checkUpdate", {
delayInMinutes: 0,
periodInMinutes: 8 * 60,
});
// 监听配置变化 // 监听配置变化
this.mq.subscribe("systemConfigChange", (msg) => { this.mq.subscribe("systemConfigChange", (msg) => {
@ -95,5 +106,31 @@ export default class ServiceWorkerManager {
systemConfig.getCloudSync().then((config) => { systemConfig.getCloudSync().then((config) => {
synchronize.cloudSyncConfigChange(config); synchronize.cloudSyncConfigChange(config);
}); });
if (process.env.NODE_ENV === "production") {
chrome.runtime.onInstalled.addListener((details) => {
if (details.reason === "install") {
chrome.tabs.create({ url: "https://docs.scriptcat.org/" });
} else if (details.reason === "update") {
chrome.tabs.create({
url: `https://docs.scriptcat.org/docs/change/#${ExtVersion}`,
});
}
});
}
}
checkUpdate() {
fetch(`${ExtServer}api/v1/system/version?version=${ExtVersion}`)
.then((resp) => resp.json())
.then((resp: { data: { notice: string; version: string } }) => {
systemConfig.getCheckUpdate().then((items) => {
if (items.notice !== resp.data.notice) {
systemConfig.setCheckUpdate(Object.assign(resp.data, { isRead: false }));
} else {
systemConfig.setCheckUpdate(Object.assign(resp.data, { isRead: items.isRead }));
}
});
});
} }
} }

View File

@ -257,7 +257,7 @@ export class ResourceService {
return fetch(u.url) return fetch(u.url)
.then(async (resp) => { .then(async (resp) => {
if (resp.status !== 200) { if (resp.status !== 200) {
throw new Error(`resource response status not 200:${resp.status}`); throw new Error(`resource response status not 200: ${resp.status}`);
} }
return { return {
data: await resp.blob(), data: await resp.blob(),

View File

@ -1,4 +1,4 @@
import { MessageQueue } from "@Packages/message/message_queue"; import { MessageQueue, Unsubscribe } from "@Packages/message/message_queue";
import { ExtMessageSender, GetSender, Group, MessageSend } from "@Packages/message/server"; import { ExtMessageSender, GetSender, Group, MessageSend } from "@Packages/message/server";
import { import {
Script, Script,
@ -15,18 +15,17 @@ import { subscribeScriptDelete, subscribeScriptEnable, subscribeScriptInstall }
import { ScriptService } from "./script"; import { ScriptService } from "./script";
import { runScript, stopScript } from "../offscreen/client"; import { runScript, stopScript } from "../offscreen/client";
import { getRunAt } from "./utils"; import { getRunAt } from "./utils";
import { randomString } from "@App/pkg/utils/utils"; import { isUserScriptsAvailable, randomString } from "@App/pkg/utils/utils";
import Cache from "@App/app/cache"; import Cache from "@App/app/cache";
import { dealPatternMatches, UrlMatch } from "@App/pkg/utils/match"; import { dealPatternMatches, UrlMatch } from "@App/pkg/utils/match";
import { ExtensionContentMessageSend } from "@Packages/message/extension_message"; import { ExtensionContentMessageSend } from "@Packages/message/extension_message";
import { sendMessage } from "@Packages/message/client"; import { sendMessage } from "@Packages/message/client";
import { compileInjectScript } from "../content/utils"; import { compileInjectScript } from "../content/utils";
import { PopupService } from "./popup";
import Logger from "@App/app/logger/logger";
import LoggerCore from "@App/app/logger/core"; import LoggerCore from "@App/app/logger/core";
import PermissionVerify from "./permission_verify"; import PermissionVerify from "./permission_verify";
import { SystemConfig } from "@App/pkg/config/config"; import { SystemConfig } from "@App/pkg/config/config";
import { ResourceService } from "./resource"; import { ResourceService } from "./resource";
import { LocalStorageDAO } from "@App/app/repo/localStorage";
// 为了优化性能存储到缓存时删除了code、value与resource // 为了优化性能存储到缓存时删除了code、value与resource
export interface ScriptMatchInfo extends ScriptRunResouce { export interface ScriptMatchInfo extends ScriptRunResouce {
@ -49,6 +48,9 @@ export class RuntimeService {
scriptCustomizeMatch: UrlMatch<string> = new UrlMatch<string>(); scriptCustomizeMatch: UrlMatch<string> = new UrlMatch<string>();
scriptMatchCache: Map<string, ScriptMatchInfo> | null | undefined; scriptMatchCache: Map<string, ScriptMatchInfo> | null | undefined;
isEnableDeveloperMode = false;
isEnableUserscribe = true;
constructor( constructor(
private systemConfig: SystemConfig, private systemConfig: SystemConfig,
private group: Group, private group: Group,
@ -70,8 +72,35 @@ export class RuntimeService {
this.group.on("runScript", this.runScript.bind(this)); this.group.on("runScript", this.runScript.bind(this));
this.group.on("pageLoad", this.pageLoad.bind(this)); this.group.on("pageLoad", this.pageLoad.bind(this));
// 读取inject.js注入页面 // 检查是否开启了开发者模式
this.registerInjectScript(); this.isEnableDeveloperMode = isUserScriptsAvailable();
if (!this.isEnableDeveloperMode) {
// 未开启加上警告引导
// 判断是否首次
const localStorage = new LocalStorageDAO();
localStorage.get("firstShowDeveloperMode").then((res) => {
if (!res) {
localStorage.save({
key: "firstShowDeveloperMode",
value: true,
});
// 打开页面
chrome.tabs.create({
url: `https://docs.scriptcat.org/docs/use/open-dev/`,
});
}
});
chrome.action.setBadgeBackgroundColor({
color: "#ff8c00",
});
chrome.action.setBadgeTextColor({
color: "#ffffff",
});
chrome.action.setBadgeText({
text: "!",
});
}
// 监听脚本开启 // 监听脚本开启
subscribeScriptEnable(this.mq, async (data) => { subscribeScriptEnable(this.mq, async (data) => {
const script = await this.scriptDAO.getAndCode(data.uuid); const script = await this.scriptDAO.getAndCode(data.uuid);
@ -82,6 +111,7 @@ export class RuntimeService {
// 如果是后台脚本, 在offscreen中进行处理 // 如果是后台脚本, 在offscreen中进行处理
if (script.type === SCRIPT_TYPE_NORMAL) { if (script.type === SCRIPT_TYPE_NORMAL) {
// 加载页面脚本 // 加载页面脚本
// 不管开没开启都要加载一次脚本信息
await this.loadPageScript(script); await this.loadPageScript(script);
if (!data.enable) { if (!data.enable) {
await this.unregistryPageScript(script.uuid); await this.unregistryPageScript(script.uuid);
@ -104,6 +134,32 @@ export class RuntimeService {
this.deleteScriptMatch(uuid); this.deleteScriptMatch(uuid);
}); });
this.systemConfig.addListener("enable_script", (enable) => {
this.isEnableUserscribe = enable;
if (enable) {
this.registerUserscripts();
} else {
this.unregisterUserscripts();
}
});
// 检查是否开启
this.isEnableUserscribe = await this.systemConfig.getEnableScript();
if (this.isEnableUserscribe) {
this.registerUserscripts();
}
}
unsubscribe: Unsubscribe[] = [];
// 取消脚本注册
unregisterUserscripts() {
chrome.userScripts.unregister();
this.deleteMessageFlag();
}
async registerUserscripts() {
// 读取inject.js注入页面
this.registerInjectScript();
// 将开启的脚本发送一次enable消息 // 将开启的脚本发送一次enable消息
const scriptDao = new ScriptDAO(); const scriptDao = new ScriptDAO();
const list = await scriptDao.all(); const list = await scriptDao.all();
@ -132,6 +188,14 @@ export class RuntimeService {
}); });
} }
deleteMessageFlag() {
return Cache.getInstance().del("scriptInjectMessageFlag");
}
getMessageFlag() {
return Cache.getInstance().get("scriptInjectMessageFlag");
}
// 给指定tab发送消息 // 给指定tab发送消息
sendMessageToTab(to: ExtMessageSender, action: string, data: any) { sendMessageToTab(to: ExtMessageSender, action: string, data: any) {
if (to.tabId === -1) { if (to.tabId === -1) {
@ -205,7 +269,7 @@ export class RuntimeService {
return undefined; return undefined;
} }
// 如果是iframe,判断是否允许在iframe里运行 // 如果是iframe,判断是否允许在iframe里运行
if (chromeSender.frameId !== undefined) { if (chromeSender.frameId) {
if (scriptRes.metadata.noframes) { if (scriptRes.metadata.noframes) {
return undefined; return undefined;
} }
@ -254,19 +318,19 @@ export class RuntimeService {
} }
// 注册inject.js // 注册inject.js
registerInjectScript() { async registerInjectScript() {
chrome.userScripts.getScripts({ ids: ["scriptcat-inject"] }).then((res) => { // 如果没设置过, 则更新messageFlag
if (res.length == 0) { let messageFlag = await this.getMessageFlag();
if (!messageFlag) {
messageFlag = await this.messageFlag();
const injectJs = await fetch("inject.js").then((res) => res.text());
// 替换ScriptFlag
const code = `(function (MessageFlag) {\n${injectJs}\n})('${messageFlag}')`;
chrome.userScripts.configureWorld({ chrome.userScripts.configureWorld({
csp: "script-src 'self' 'unsafe-inline' 'unsafe-eval' *", csp: "script-src 'self' 'unsafe-inline' 'unsafe-eval' *",
messaging: true, messaging: true,
}); });
fetch("inject.js") const scripts: chrome.userScripts.RegisteredUserScript[] = [
.then((res) => res.text())
.then(async (injectJs) => {
// 替换ScriptFlag
const code = `(function (MessageFlag) {\n${injectJs}\n})('${await this.messageFlag()}')`;
chrome.userScripts.register([
{ {
id: "scriptcat-inject", id: "scriptcat-inject",
js: [{ code }], js: [{ code }],
@ -284,11 +348,28 @@ export class RuntimeService {
runAt: "document_start", runAt: "document_start",
world: "USER_SCRIPT", world: "USER_SCRIPT",
}, },
]); ];
try {
// 如果使用getScripts来判断, 会出现找不到的问题
// 另外如果使用
await chrome.userScripts.register(scripts);
} catch (e: any) {
LoggerCore.logger().error("register inject.js error", {
error: e,
});
if (e.message?.indexOf("Duplicate script ID") !== -1) {
// 如果是重复注册, 则更新
chrome.userScripts.update(scripts, () => {
if (chrome.runtime.lastError) {
LoggerCore.logger().error("update inject.js error", {
error: chrome.runtime.lastError,
}); });
} }
}); });
} }
}
}
}
loadingScript: Promise<void> | null | undefined; loadingScript: Promise<void> | null | undefined;
@ -367,9 +448,12 @@ export class RuntimeService {
if (!this.scriptMatchCache) { if (!this.scriptMatchCache) {
await this.loadScriptMatchInfo(); await this.loadScriptMatchInfo();
} }
this.scriptMatchCache!.get(uuid)!.status = status; const script = await this.scriptMatchCache!.get(uuid);
if (script) {
script.status = status;
this.saveScriptMatchInfo(); this.saveScriptMatchInfo();
} }
}
async deleteScriptMatch(uuid: string) { async deleteScriptMatch(uuid: string) {
if (!this.scriptMatchCache) { if (!this.scriptMatchCache) {
@ -434,26 +518,37 @@ export class RuntimeService {
this.addScriptMatch(scriptMatchInfo); this.addScriptMatch(scriptMatchInfo);
// 如果脚本开启, 则注册脚本 // 如果脚本开启, 则注册脚本
if (script.status === SCRIPT_STATUS_ENABLE) { if (this.isEnableDeveloperMode && this.isEnableUserscribe && script.status === SCRIPT_STATUS_ENABLE) {
if (!scriptRes.metadata["noframes"]) { if (scriptRes.metadata["noframes"]) {
registerScript.allFrames = false;
} else {
registerScript.allFrames = true; registerScript.allFrames = true;
} }
if (scriptRes.metadata["run-at"]) { if (scriptRes.metadata["run-at"]) {
registerScript.runAt = getRunAt(scriptRes.metadata["run-at"]); registerScript.runAt = getRunAt(scriptRes.metadata["run-at"]);
} }
if (await Cache.getInstance().get("registryScript:" + script.uuid)) { const res = await chrome.userScripts.getScripts({ ids: [script.uuid] });
await chrome.userScripts.update([registerScript]); const logger = LoggerCore.logger({
} else {
await chrome.userScripts.register([registerScript], () => {
if (chrome.runtime.lastError) {
LoggerCore.logger().error("registerScript error", {
error: chrome.runtime.lastError,
name: script.name, name: script.name,
registerMatch: { registerMatch: {
matches: registerScript.matches, matches: registerScript.matches,
excludeMatches: registerScript.excludeMatches, excludeMatches: registerScript.excludeMatches,
}, },
}); });
if (res.length > 0) {
await chrome.userScripts.update([registerScript], () => {
if (chrome.runtime.lastError) {
logger.error("update registerScript error", {
error: chrome.runtime.lastError,
});
}
});
} else {
await chrome.userScripts.register([registerScript], () => {
if (chrome.runtime.lastError) {
logger.error("registerScript error", {
error: chrome.runtime.lastError,
});
} }
}); });
} }
@ -462,19 +557,17 @@ export class RuntimeService {
} }
async unregistryPageScript(uuid: string) { async unregistryPageScript(uuid: string) {
if (!(await Cache.getInstance().get("registryScript:" + uuid))) { if (
!this.isEnableDeveloperMode ||
!this.isEnableUserscribe ||
!(await Cache.getInstance().get("registryScript:" + uuid))
) {
return; return;
} }
chrome.userScripts.unregister(
{
ids: [uuid],
},
() => {
// 删除缓存 // 删除缓存
Cache.getInstance().del("registryScript:" + uuid); Cache.getInstance().del("registryScript:" + uuid);
// 修改脚本状态为disable // 修改脚本状态为disable
this.updateScriptStatus(uuid, SCRIPT_STATUS_DISABLE); this.updateScriptStatus(uuid, SCRIPT_STATUS_DISABLE);
} chrome.userScripts.unregister({ ids: [uuid] });
);
} }
} }

View File

@ -21,6 +21,7 @@ import { ResourceService } from "./resource";
import { ValueService } from "./value"; import { ValueService } from "./value";
import { compileScriptCode } from "../content/utils"; import { compileScriptCode } from "../content/utils";
import { SystemConfig } from "@App/pkg/config/config"; import { SystemConfig } from "@App/pkg/config/config";
import i18n, { localePath } from "@App/locales/locales";
export class ScriptService { export class ScriptService {
logger: Logger; logger: Logger;
@ -59,16 +60,10 @@ export class ScriptService {
// 读取脚本url内容, 进行安装 // 读取脚本url内容, 进行安装
const logger = this.logger.with({ url: targetUrl }); const logger = this.logger.with({ url: targetUrl });
logger.debug("install script"); logger.debug("install script");
this.openInstallPageByUrl(targetUrl, "user").catch((e) => { this.openInstallPageByUrl(targetUrl, "user")
.catch((e) => {
logger.error("install script error", Logger.E(e)); logger.error("install script error", Logger.E(e));
// 如果打开失败, 则重定向到安装页 // 不再重定向当前url
chrome.scripting.executeScript({
target: { tabId: req.tabId },
func: function () {
history.back();
},
});
// 并不再重定向当前url
chrome.declarativeNetRequest.updateDynamicRules( chrome.declarativeNetRequest.updateDynamicRules(
{ {
removeRuleIds: [2], removeRuleIds: [2],
@ -93,16 +88,27 @@ export class ScriptService {
} }
} }
); );
})
.finally(() => {
// 回退到到安装页
chrome.scripting.executeScript({
target: { tabId: req.tabId },
func: function () {
history.back();
},
});
}); });
}, },
{ {
urls: [ urls: [
"https://docs.scriptcat.org/docs/script_installation", "https://docs.scriptcat.org/docs/script_installation/",
"https://docs.scriptcat.org/en/docs/script_installation/",
"https://www.tampermonkey.net/script_installation.php", "https://www.tampermonkey.net/script_installation.php",
], ],
types: ["main_frame"], types: ["main_frame"],
} }
); );
// 获取i18n
// 重定向到脚本安装页 // 重定向到脚本安装页
chrome.declarativeNetRequest.updateDynamicRules( chrome.declarativeNetRequest.updateDynamicRules(
{ {
@ -114,7 +120,7 @@ export class ScriptService {
action: { action: {
type: chrome.declarativeNetRequest.RuleActionType.REDIRECT, type: chrome.declarativeNetRequest.RuleActionType.REDIRECT,
redirect: { redirect: {
regexSubstitution: "https://docs.scriptcat.org/docs/script_installation#url=\\0", regexSubstitution: `https://docs.scriptcat.org${localePath}/docs/script_installation/#url=\\0`,
}, },
}, },
condition: { condition: {
@ -479,6 +485,15 @@ export class ScriptService {
return this.checkUpdate(uuid, "user"); return this.checkUpdate(uuid, "user");
} }
isInstalled({ name, namespace }: { name: string; namespace: string }) {
return this.scriptDAO.findByNameAndNamespace(name, namespace).then((script) => {
if (script) {
return { installed: true, version: script.metadata.version && script.metadata.version[0] };
}
return { installed: false };
});
}
init() { init() {
this.listenerScriptInstall(); this.listenerScriptInstall();
@ -494,6 +509,7 @@ export class ScriptService {
this.group.on("resetMatch", this.resetMatch.bind(this)); this.group.on("resetMatch", this.resetMatch.bind(this));
this.group.on("resetExclude", this.resetExclude.bind(this)); this.group.on("resetExclude", this.resetExclude.bind(this));
this.group.on("requestCheckUpdate", this.requestCheckUpdate.bind(this)); this.group.on("requestCheckUpdate", this.requestCheckUpdate.bind(this));
this.group.on("isInstalled", this.isInstalled.bind(this));
// 定时检查更新, 每10分钟检查一次 // 定时检查更新, 每10分钟检查一次
chrome.alarms.create("checkScriptUpdate", { chrome.alarms.create("checkScriptUpdate", {

View File

@ -27,10 +27,15 @@ i18n.use(initReactI18next).init({
}, },
}); });
export let localePath = "";
chrome.i18n.getAcceptLanguages((lngs) => { chrome.i18n.getAcceptLanguages((lngs) => {
systemConfig.getLanguage().then((lng) => { systemConfig.getLanguage(lngs).then((lng) => {
i18n.changeLanguage(lng); i18n.changeLanguage(lng);
dayjs.locale(lng.toLocaleLowerCase()); dayjs.locale(lng.toLocaleLowerCase());
if (lng !== "zh-CN") {
localePath = "en";
}
}); });
}); });

View File

@ -368,5 +368,8 @@
"eslint_config_format_error": "eslint配置格式错误", "eslint_config_format_error": "eslint配置格式错误",
"export_success": "导出成功", "export_success": "导出成功",
"get_backup_dir_url_failed": "获取备份目录地址失败", "get_backup_dir_url_failed": "获取备份目录地址失败",
"get_backup_files_failed": "获取备份文件失败" "get_backup_files_failed": "获取备份文件失败",
"develop_mode_guide": "检测到当前未开启开发者模式,您的脚本无法正常使用,<a href=\"https://docs.scriptcat.org/docs/use/open-dev/\" target=\"black\" style=\"color: var(--color-text-1)\">👉点我了解如何开启</a>",
"enable_script_failed": "脚本开启失败",
"disable_script_failed": "脚本关闭失败"
} }

View File

@ -1,7 +1,7 @@
{ {
"manifest_version": 3, "manifest_version": 3,
"name": "__MSG_scriptcat__", "name": "__MSG_scriptcat__",
"version": "0.17.0.1003", "version": "0.17.0.1005",
"author": "CodFrm", "author": "CodFrm",
"description": "__MSG_scriptcat_description__", "description": "__MSG_scriptcat_description__",
"options_ui": { "options_ui": {

View File

@ -39,11 +39,9 @@ const CodeEditor: React.ForwardRefRenderFunction<{ editor: editor.IStandaloneCod
}, []); }, []);
useEffect(() => { useEffect(() => {
console.log("1231", code);
if (diffCode === undefined || code === undefined || !div.current) { if (diffCode === undefined || code === undefined || !div.current) {
return () => {}; return () => {};
} }
console.log("1232");
let edit: editor.IStandaloneDiffEditor | editor.IStandaloneCodeEditor; let edit: editor.IStandaloneDiffEditor | editor.IStandaloneCodeEditor;
const inlineDiv = document.getElementById(id) as HTMLDivElement; const inlineDiv = document.getElementById(id) as HTMLDivElement;
// @ts-ignore // @ts-ignore

View File

@ -81,6 +81,8 @@ import {
requestStopScript, requestStopScript,
requestRunScript, requestRunScript,
scriptClient, scriptClient,
enableLoading,
updateEnableStatus,
} from "@App/pages/store/features/script"; } from "@App/pages/store/features/script";
import { message, systemConfig } from "@App/pages/store/global"; import { message, systemConfig } from "@App/pages/store/global";
import { SynchronizeClient, ValueClient } from "@App/app/service/service_worker/client"; import { SynchronizeClient, ValueClient } from "@App/app/service/service_worker/client";
@ -615,6 +617,7 @@ function ScriptList() {
const dealColumns: ColumnProps[] = []; const dealColumns: ColumnProps[] = [];
newColumns.forEach((item) => { newColumns.forEach((item) => {
console.log(newColumns);
switch (item.width) { switch (item.width) {
case -1: case -1:
break; break;
@ -625,8 +628,9 @@ function ScriptList() {
}); });
const sortIndex = dealColumns.findIndex((item) => item.key === "sort"); const sortIndex = dealColumns.findIndex((item) => item.key === "sort");
let SortableItem;
const SortableItem = (props: any) => { if (sortIndex !== -1) {
SortableItem = (props: any) => {
const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: props!.record.uuid }); const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: props!.record.uuid });
const style = { const style = {
@ -656,6 +660,7 @@ function ScriptList() {
return <tr ref={setNodeRef} style={style} {...attributes} {...props} />; return <tr ref={setNodeRef} style={style} {...attributes} {...props} />;
}; };
}
const components: ComponentsProps = { const components: ComponentsProps = {
table: React.forwardRef(SortableWrapper), table: React.forwardRef(SortableWrapper),
@ -703,19 +708,23 @@ function ScriptList() {
type="primary" type="primary"
size="mini" size="mini"
onClick={() => { onClick={() => {
const uuids: string[] = []; const enableAction = (enable: boolean) => {
const uuids = select.map((item) => item.uuid);
dispatch(enableLoading({ uuids: uuids, loading: true }));
Promise.allSettled(uuids.map((uuid) => scriptClient.enable(uuid, enable))).finally(() => {
dispatch(updateEnableStatus({ uuids: uuids, enable: enable }));
dispatch(enableLoading({ uuids: uuids, loading: false }));
});
};
switch (action) { switch (action) {
case "enable": case "enable":
select.forEach((item) => { enableAction(true);
dispatch(requestEnableScript({ uuid: item.uuid, enable: true }));
});
break; break;
case "disable": case "disable":
select.forEach((item) => { enableAction(false);
dispatch(requestEnableScript({ uuid: item.uuid, enable: false }));
});
break; break;
case "export": case "export":
const uuids: string[] = [];
select.forEach((item) => { select.forEach((item) => {
uuids.push(item.uuid); uuids.push(item.uuid);
}); });

View File

@ -30,7 +30,7 @@ function Tools() {
useEffect(() => { useEffect(() => {
// 获取配置 // 获取配置
const loadConfig = async () => { const loadConfig = async () => {
const [backup, vscodeUrl] = await Promise.all([ const [backup, vscodeUrl, vscodeReconnect] = await Promise.all([
systemConfig.getBackup(), systemConfig.getBackup(),
systemConfig.getVscodeUrl(), systemConfig.getVscodeUrl(),
systemConfig.getVscodeReconnect(), systemConfig.getVscodeReconnect(),
@ -38,7 +38,7 @@ function Tools() {
setFilesystemType(backup.filesystem); setFilesystemType(backup.filesystem);
setFilesystemParam(backup.params[backup.filesystem] || {}); setFilesystemParam(backup.params[backup.filesystem] || {});
setVscodeUrl(vscodeUrl); setVscodeUrl(vscodeUrl);
setVscodeReconnect(systemConfig.vscodeReconnect); setVscodeReconnect(vscodeReconnect);
}; };
loadConfig(); loadConfig();
}, []); }, []);

View File

@ -1,4 +1,4 @@
import { Script, ScriptAndCode, ScriptCodeDAO, ScriptDAO } from "@App/app/repo/scripts"; import { Script, SCRIPT_TYPE_NORMAL, ScriptAndCode, ScriptCodeDAO, ScriptDAO } from "@App/app/repo/scripts";
import CodeEditor from "@App/pages/components/CodeEditor"; import CodeEditor from "@App/pages/components/CodeEditor";
import React, { useCallback, useEffect, useRef, useState } from "react"; import React, { useCallback, useEffect, useRef, useState } from "react";
import { useNavigate, useParams, useSearchParams } from "react-router-dom"; import { useNavigate, useParams, useSearchParams } from "react-router-dom";
@ -16,7 +16,7 @@ import { prepareScriptByCode } from "@App/pkg/utils/script";
import ScriptStorage from "@App/pages/components/ScriptStorage"; import ScriptStorage from "@App/pages/components/ScriptStorage";
import ScriptResource from "@App/pages/components/ScriptResource"; import ScriptResource from "@App/pages/components/ScriptResource";
import ScriptSetting from "@App/pages/components/ScriptSetting"; import ScriptSetting from "@App/pages/components/ScriptSetting";
import { scriptClient } from "@App/pages/store/features/script"; import { runtimeClient, scriptClient } from "@App/pages/store/features/script";
import { i18nName } from "@App/locales/locales"; import { i18nName } from "@App/locales/locales";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
@ -188,16 +188,16 @@ function ScriptEditor() {
const save = (script: Script, e: editor.IStandaloneCodeEditor): Promise<Script> => { const save = (script: Script, e: editor.IStandaloneCodeEditor): Promise<Script> => {
// 解析code生成新的script并更新 // 解析code生成新的script并更新
return new Promise(() => { return prepareScriptByCode(e.getValue(), script.origin || "", script.uuid)
prepareScriptByCode(e.getValue(), script.origin || "", script.uuid)
.then((prepareScript) => { .then((prepareScript) => {
const newScript = prepareScript.script; const newScript = prepareScript.script;
if (!newScript.name) { if (!newScript.name) {
Message.warning(t("script_name_cannot_be_set_to_empty")); Message.warning(t("script_name_cannot_be_set_to_empty"));
return; return Promise.reject(new Error("script name cannot be empty"));
} }
scriptClient.install(newScript, e.getValue()).then( return scriptClient
(update) => { .install(newScript, e.getValue())
.then((update): Script => {
if (!update) { if (!update) {
Message.success("新建成功,请注意后台脚本不会默认开启"); Message.success("新建成功,请注意后台脚本不会默认开启");
// 保存的时候如何左侧没有脚本即新建 // 保存的时候如何左侧没有脚本即新建
@ -207,7 +207,6 @@ function ScriptEditor() {
}); });
} else { } else {
setScriptList((prev) => { setScriptList((prev) => {
// eslint-disable-next-line no-shadow, array-callback-return
prev.map((script: Script) => { prev.map((script: Script) => {
if (script.uuid === newScript.uuid) { if (script.uuid === newScript.uuid) {
script.name = newScript.name; script.name = newScript.name;
@ -228,17 +227,19 @@ function ScriptEditor() {
} }
return [...prev]; return [...prev];
}); });
}, return newScript;
(err: any) => { })
.catch((err: any) => {
Message.error(`保存失败: ${err}`); Message.error(`保存失败: ${err}`);
} return Promise.reject(err);
); });
}) })
.catch((err) => { .catch((err) => {
Message.error(`错误的脚本代码: ${err}`); Message.error(`错误的脚本代码: ${err}`);
}); return Promise.reject(err);
}); });
}; };
const saveAs = (script: Script, e: editor.IStandaloneCodeEditor) => { const saveAs = (script: Script, e: editor.IStandaloneCodeEditor) => {
return new Promise<void>((resolve) => { return new Promise<void>((resolve) => {
chrome.downloads.download( chrome.downloads.download(
@ -289,30 +290,35 @@ function ScriptEditor() {
title: t("run"), title: t("run"),
items: [ items: [
{ {
id: "debug", id: "run",
title: t("debug"), title: t("run"),
hotKey: KeyMod.CtrlCmd | KeyCode.F5, hotKey: KeyMod.CtrlCmd | KeyCode.F5,
hotKeyString: "Ctrl+F5", hotKeyString: "Ctrl+F5",
tooltip: "只有后台脚本/定时脚本才能调试, 且调试模式下不对进行权限校验(例如@connect)", tooltip: "只有后台脚本/定时脚本才能运行",
action: async (script, e) => { action: async (script, e) => {
// 保存更新代码之后再调试 // 保存更新代码之后再调试
const newScript = await save(script, e); const newScript = await save(script, e);
// 判断脚本类型
if (newScript.type === SCRIPT_TYPE_NORMAL) {
Message.error("只有后台脚本/定时脚本才能运行");
return;
}
Message.loading({ Message.loading({
id: "debug_script", id: "debug_script",
content: "正在准备脚本资源...", content: "正在准备脚本资源...",
duration: 3000, duration: 3000,
}); });
runtimeCtrl runtimeClient
.debugScript(newScript) .runScript(newScript.uuid)
.then(() => { .then(() => {
Message.success({ Message.success({
id: "debug_script", id: "debug_script",
content: "构建成功, 可以打开开发者工具在控制台中查看输出", content: "构建成功, 可以在扩展页打开开发者工具在控制台中查看输出",
duration: 3000, duration: 3000,
}); });
}) })
.catch((err) => { .catch((err) => {
LoggerCore.logger(Logger.E(err)).debug("debug script error"); LoggerCore.logger(Logger.E(err)).debug("run script error");
Message.error({ Message.error({
id: "debug_script", id: "debug_script",
content: `构建失败: ${err}`, content: `构建失败: ${err}`,

View File

@ -11,12 +11,14 @@ import {
IconSearch, IconSearch,
} from "@arco-design/web-react/icon"; } from "@arco-design/web-react/icon";
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import { RiMessage2Line } from "react-icons/ri"; import { RiMessage2Line, RiZzzFill } from "react-icons/ri";
import semver from "semver"; import semver from "semver";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import ScriptMenuList from "../components/ScriptMenuList"; import ScriptMenuList from "../components/ScriptMenuList";
import { popupClient } from "../store/features/script"; import { popupClient } from "../store/features/script";
import { ScriptMenu } from "@App/app/service/service_worker/popup"; import { ScriptMenu } from "@App/app/service/service_worker/popup";
import { systemConfig } from "../store/global";
import { isUserScriptsAvailable } from "@App/pkg/utils/utils";
const CollapseItem = Collapse.Item; const CollapseItem = Collapse.Item;
@ -30,11 +32,13 @@ function App() {
const [scriptList, setScriptList] = useState<ScriptMenu[]>([]); const [scriptList, setScriptList] = useState<ScriptMenu[]>([]);
const [backScriptList, setBackScriptList] = useState<ScriptMenu[]>([]); const [backScriptList, setBackScriptList] = useState<ScriptMenu[]>([]);
const [showAlert, setShowAlert] = useState(false); const [showAlert, setShowAlert] = useState(false);
const [notice, setNotice] = useState(""); const [checkUpdate, setCheckUpdate] = useState<Parameters<typeof systemConfig.setCheckUpdate>[0]>({
const [isRead, setIsRead] = useState(true); version: ExtVersion,
const [version, setVersion] = useState(ExtVersion); notice: "",
isRead: false,
});
const [currentUrl, setCurrentUrl] = useState(""); const [currentUrl, setCurrentUrl] = useState("");
const [isEnableScript, setIsEnableScript] = useState(localStorage.enable_script !== "false"); const [isEnableScript, setIsEnableScript] = useState(true);
const { t } = useTranslation(); const { t } = useTranslation();
let url: URL | undefined; let url: URL | undefined;
@ -45,22 +49,21 @@ function App() {
} }
useEffect(() => { useEffect(() => {
// systemManage.getNotice().then((res) => { const loadConfig = async () => {
// if (res) { const [isEnableScript, checkUpdate] = await Promise.all([
// setNotice(res.notice); systemConfig.getEnableScript(),
// setIsRead(res.isRead); systemConfig.getCheckUpdate(),
// } ]);
// }); setIsEnableScript(isEnableScript);
// systemManage.getVersion().then((res) => { setCheckUpdate(checkUpdate);
// res && setVersion(res); };
// }); loadConfig();
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (!tabs.length) { if (!tabs.length) {
return; return;
} }
setCurrentUrl(tabs[0].url || ""); setCurrentUrl(tabs[0].url || "");
popupClient.getPopupData({ url: tabs[0].url!, tabId: tabs[0].id! }).then((resp) => { popupClient.getPopupData({ url: tabs[0].url!, tabId: tabs[0].id! }).then((resp) => {
console.log(resp);
// 按照开启状态和更新时间排序 // 按照开启状态和更新时间排序
const list = resp.scriptList; const list = resp.scriptList;
list.sort((a, b) => { list.sort((a, b) => {
@ -82,6 +85,10 @@ function App() {
}); });
}, []); }, []);
return ( return (
<>
{!isUserScriptsAvailable() && (
<Alert type="warning" content={<div dangerouslySetInnerHTML={{ __html: t("develop_mode_guide") }} />} />
)}
<Card <Card
size="small" size="small"
title={ title={
@ -94,9 +101,9 @@ function App() {
onChange={(val) => { onChange={(val) => {
setIsEnableScript(val); setIsEnableScript(val);
if (val) { if (val) {
localStorage.enable_script = "true"; systemConfig.setEnableScript(true);
} else { } else {
localStorage.enable_script = "false"; systemConfig.setEnableScript(false);
} }
}} }}
/> />
@ -109,15 +116,16 @@ function App() {
window.open("/src/options.html", "_blank"); window.open("/src/options.html", "_blank");
}} }}
/> />
<Badge count={isRead ? 0 : 1} dot offset={[-8, 6]}> <Badge count={checkUpdate.isRead ? 0 : 1} dot offset={[-8, 6]}>
<Button <Button
type="text" type="text"
icon={<IconNotification />} icon={<IconNotification />}
iconOnly iconOnly
onClick={() => { onClick={() => {
setShowAlert(!showAlert); setShowAlert(!showAlert);
setIsRead(true); checkUpdate.isRead = true;
systemManage.setRead(true); setCheckUpdate(checkUpdate);
systemConfig.setCheckUpdate(checkUpdate);
}} }}
/> />
</Badge> </Badge>
@ -179,9 +187,9 @@ function App() {
bodyStyle={{ padding: 0 }} bodyStyle={{ padding: 0 }}
> >
<Alert <Alert
style={{ marginBottom: 20, display: showAlert ? "flex" : "none" }} style={{ display: showAlert ? "flex" : "none" }}
type="info" type="info"
content={<div dangerouslySetInnerHTML={{ __html: notice }} />} content={<div dangerouslySetInnerHTML={{ __html: checkUpdate.notice || "" }} />}
/> />
<Collapse bordered={false} defaultActiveKey={["script", "background"]} style={{ maxWidth: 640 }}> <Collapse bordered={false} defaultActiveKey={["script", "background"]} style={{ maxWidth: 640 }}>
<CollapseItem <CollapseItem
@ -204,10 +212,10 @@ function App() {
</Collapse> </Collapse>
<div className="flex flex-row arco-card-header !h-6"> <div className="flex flex-row arco-card-header !h-6">
<span className="text-[12px] font-500">{`v${ExtVersion}`}</span> <span className="text-[12px] font-500">{`v${ExtVersion}`}</span>
{semver.lt(ExtVersion, version) && ( {semver.lt(ExtVersion, checkUpdate.version) && (
<span <span
onClick={() => { onClick={() => {
window.open(`https://github.com/scriptscat/scriptcat/releases/tag/v${version}`); window.open(`https://github.com/scriptscat/scriptcat/releases/tag/v${checkUpdate.version}`);
}} }}
className="text-1 font-500" className="text-1 font-500"
style={{ cursor: "pointer" }} style={{ cursor: "pointer" }}
@ -217,6 +225,7 @@ function App() {
)} )}
</div> </div>
</Card> </Card>
</>
); );
} }

View File

@ -102,6 +102,22 @@ export const scriptSlice = createAppSlice({
script.runStatus = action.payload.runStatus; script.runStatus = action.payload.runStatus;
} }
}, },
updateEnableStatus: (state, action: PayloadAction<{ uuids: string[]; enable: boolean }>) => {
state.scripts = state.scripts.map((s) => {
if (action.payload.uuids.includes(s.uuid)) {
s.status = action.payload.enable ? SCRIPT_STATUS_ENABLE : SCRIPT_STATUS_DISABLE;
}
return s;
});
},
enableLoading(state, action: PayloadAction<{ uuids: string[]; loading: boolean }>) {
state.scripts = state.scripts.map((s) => {
if (action.payload.uuids.includes(s.uuid)) {
s.enableLoading = action.payload.loading;
}
return s;
});
},
}, },
extraReducers: (builder) => { extraReducers: (builder) => {
builder builder
@ -144,6 +160,6 @@ export const scriptSlice = createAppSlice({
}, },
}); });
export const { sortScript, upsertScript, deleteScript } = scriptSlice.actions; export const { sortScript, upsertScript, deleteScript, enableLoading, updateEnableStatus } = scriptSlice.actions;
export const { selectScripts } = scriptSlice.selectors; export const { selectScripts } = scriptSlice.selectors;

View File

@ -5,6 +5,7 @@ import { FileSystemType } from "@Packages/filesystem/factory";
import { MessageQueue } from "@Packages/message/message_queue"; import { MessageQueue } from "@Packages/message/message_queue";
import i18n from "@App/locales/locales"; import i18n from "@App/locales/locales";
import dayjs from "dayjs"; import dayjs from "dayjs";
import { ExtVersion } from "@App/app/const";
export const SystamConfigChange = "systemConfigChange"; export const SystamConfigChange = "systemConfigChange";
@ -34,8 +35,11 @@ export class SystemConfig {
} }
addListener(key: string, callback: (value: any) => void) { addListener(key: string, callback: (value: any) => void) {
this.mq.subscribe(key, (msg) => { this.mq.subscribe(SystamConfigChange, (data: { key: string; value: string }) => {
const { value } = msg; if (data.key !== key) {
return;
}
const { value } = data;
callback(value); callback(value);
}); });
} }
@ -65,9 +69,7 @@ export class SystemConfig {
public set(key: string, val: any) { public set(key: string, val: any) {
this.cache.set(key, val); this.cache.set(key, val);
this.storage.set(key, val).then(() => { this.storage.set(key, val);
console.log(chrome.runtime.lastError, val);
});
// 发送消息通知更新 // 发送消息通知更新
this.mq.publish(SystamConfigChange, { this.mq.publish(SystamConfigChange, {
key, key,
@ -226,19 +228,20 @@ export class SystemConfig {
this.set("menu_expand_num", val); this.set("menu_expand_num", val);
} }
async getLanguage() { async getLanguage(acceptLanguages?: string[]): Promise<string> {
const defaultLanguage = await new Promise<string>((resolve) => { const defaultLanguage = await new Promise<string>(async (resolve) => {
chrome.i18n.getAcceptLanguages((lngs) => { if (!acceptLanguages) {
acceptLanguages = await chrome.i18n.getAcceptLanguages();
}
// 遍历数组寻找匹配语言 // 遍历数组寻找匹配语言
for (let i = 0; i < lngs.length; i += 1) { for (let i = 0; i < acceptLanguages.length; i += 1) {
const lng = lngs[i]; const lng = acceptLanguages[i];
if (i18n.hasResourceBundle(lng, "translation")) { if (i18n.hasResourceBundle(lng, "translation")) {
resolve(lng); resolve(lng);
break; break;
} }
} }
}); });
});
return this.get("language", defaultLanguage || chrome.i18n.getUILanguage()); return this.get("language", defaultLanguage || chrome.i18n.getUILanguage());
} }
@ -247,4 +250,28 @@ export class SystemConfig {
i18n.changeLanguage(value); i18n.changeLanguage(value);
dayjs.locale(value.toLocaleLowerCase()); dayjs.locale(value.toLocaleLowerCase());
} }
setCheckUpdate(data: { notice: string; version: string; isRead: boolean }) {
this.set("check_update", {
notice: data.notice,
version: data.version,
isRead: data.isRead,
});
}
getCheckUpdate(): Promise<Parameters<typeof this.setCheckUpdate>[0]> {
return this.get("check_update", {
notice: "",
isRead: false,
version: ExtVersion,
});
}
setEnableScript(enable: boolean) {
this.set("enable_script", enable);
}
getEnableScript(): Promise<boolean> {
return this.get("enable_script", true);
}
} }

View File

@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { dealPatternMatches, parsePatternMatchesURL, UrlMatch } from "./match"; import { dealPatternMatches, parsePatternMatchesURL, UrlMatch } from "./match";
import path from "path";
// https://developer.chrome.com/docs/extensions/mv3/match_patterns/ // https://developer.chrome.com/docs/extensions/mv3/match_patterns/
describe("UrlMatch-google", () => { describe("UrlMatch-google", () => {
@ -39,16 +40,10 @@ describe("UrlMatch-google", () => {
describe("UrlMatch-google-error", () => { describe("UrlMatch-google-error", () => {
const url = new UrlMatch<string>(); const url = new UrlMatch<string>();
it("error-1", () => { it("error-1", () => {
expect(() => {
url.add("https://*foo/bar", "ok1");
}).toThrow(Error);
});
// 从v0.17.0开始允许这种
it("error-2", () => {
url.add("https://foo.*.bar/baz", "ok1"); url.add("https://foo.*.bar/baz", "ok1");
expect(url.match("https://foo.api.bar/baz")).toEqual(["ok1"]); expect(url.match("https://foo.api.bar/baz")).toEqual(["ok1"]);
}); });
it("error-3", () => { it("error-2", () => {
expect(() => { expect(() => {
url.add("http:/bar", "ok1"); url.add("http:/bar", "ok1");
}).toThrow(Error); }).toThrow(Error);
@ -77,6 +72,13 @@ describe("UrlMatch-search", () => {
expect(url.match("http://api.bar.example.com/")).toEqual(["ok1"]); expect(url.match("http://api.bar.example.com/")).toEqual(["ok1"]);
expect(url.match("http://api.example.com/")).toEqual([]); expect(url.match("http://api.example.com/")).toEqual([]);
}); });
it("*://example*/*/example.path*", () => {
const url = new UrlMatch<string>();
url.add("*://example*/*/example.path*", "ok1");
expect(url.match("https://example.com/foo/example.path")).toEqual(["ok1"]);
expect(url.match("https://example.com/foo/bar/example.path")).toEqual(["ok1"]);
expect(url.match("https://example.com/foo/bar/example.path2")).toEqual(["ok1"]);
});
}); });
describe("UrlMatch-port1", () => { describe("UrlMatch-port1", () => {
@ -177,6 +179,12 @@ describe("parsePatternMatchesURL", () => {
host: "127.0.0.1", host: "127.0.0.1",
path: "", path: "",
}); });
const matches4 = parsePatternMatchesURL("*://*/*");
expect(matches4).toEqual({
scheme: "*",
host: "*",
path: "*",
});
}); });
it("search", () => { it("search", () => {
// 会忽略掉search部分 // 会忽略掉search部分
@ -191,7 +199,7 @@ describe("parsePatternMatchesURL", () => {
const matches = parsePatternMatchesURL("*://www.example.com*"); const matches = parsePatternMatchesURL("*://www.example.com*");
expect(matches).toEqual({ expect(matches).toEqual({
scheme: "*", scheme: "*",
host: "www.example.com", host: "*",
path: "*", path: "*",
}); });
}); });
@ -203,4 +211,24 @@ describe("parsePatternMatchesURL", () => {
path: "*", path: "*",
}); });
}); });
it("一些怪异的情况", () => {
let matches = parsePatternMatchesURL("*://*./*");
expect(matches).toEqual({
scheme: "*",
host: "*",
path: "*",
});
matches = parsePatternMatchesURL("*://example*/*");
expect(matches).toEqual({
scheme: "*",
host: "*",
path: "*",
});
matches = parsePatternMatchesURL("http*://*.example.com/*");
expect(matches).toEqual({
scheme: "*",
host: "*.example.com",
path: "*",
});
});
}); });

View File

@ -64,20 +64,11 @@ export default class Match<T> {
let pos = u.host.indexOf("*"); let pos = u.host.indexOf("*");
if (u.host === "*" || u.host === "**") { if (u.host === "*" || u.host === "**") {
pos = -1; pos = -1;
} else if (u.host.endsWith("*")) {
// 处理*结尾
if (!u.host.endsWith(":*")) {
u.host = u.host.substring(0, u.host.length - 1);
}
} }
u.host = u.host.replace(/\*/g, "[^/]*?"); u.host = u.host.replace(/\*/g, "[^/]*?");
// 处理 *.开头 // 处理 *.开头
if (u.host.startsWith("[^/]*?.")) { if (u.host.startsWith("[^/]*?.")) {
u.host = `([^/]*?\\.?)${u.host.substring(7)}`; u.host = `([^/]*?\\.?)${u.host.substring(7)}`;
} else if (pos !== -1) {
if (u.host.indexOf(".") === -1) {
return "";
}
} }
// 处理顶域 // 处理顶域
if (u.host.endsWith("tld")) { if (u.host.endsWith("tld")) {
@ -223,6 +214,7 @@ export interface PatternMatchesUrl {
} }
// 解析URL, 根据https://developer.chrome.com/docs/extensions/develop/concepts/match-patterns?hl=zh-cn进行处理 // 解析URL, 根据https://developer.chrome.com/docs/extensions/develop/concepts/match-patterns?hl=zh-cn进行处理
// 将一些异常情况直接转为通配用最大的范围去注册userScript在执行的时候再用UrlMatch去匹配过滤
export function parsePatternMatchesURL( export function parsePatternMatchesURL(
url: string, url: string,
options?: { options?: {
@ -251,6 +243,9 @@ export function parsePatternMatchesURL(
} }
} }
if (result) { if (result) {
if (result.scheme === "http*") {
result.scheme = "*";
}
if (result.host !== "*") { if (result.host !== "*") {
// *开头但是不是*.的情况 // *开头但是不是*.的情况
if (result.host.startsWith("*")) { if (result.host.startsWith("*")) {
@ -261,6 +256,10 @@ export function parsePatternMatchesURL(
} }
// 结尾是*的情况 // 结尾是*的情况
if (result.host.endsWith("*")) { if (result.host.endsWith("*")) {
result.host = "*";
}
// 结尾是.的情况
if (result.host.endsWith(".")) {
result.host = result.host.slice(0, -1); result.host = result.host.slice(0, -1);
} }
// 处理 www.*.example.com 的情况为 *.example.com // 处理 www.*.example.com 的情况为 *.example.com

View File

@ -264,3 +264,14 @@ export function errorMsg(e: any): string {
} }
return ""; return "";
} }
export function isUserScriptsAvailable() {
try {
// Property access which throws if developer mode is not enabled.
chrome.userScripts;
return true;
} catch {
// Not available.
return false;
}
}