From ff3b72192efbe8712479d9460a4f1c0bf45a6e0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E4=B8=80=E4=B9=8B?= Date: Mon, 29 Apr 2024 14:29:00 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20=E5=A4=84=E7=90=86=E5=85=A8?= =?UTF-8?q?=E5=B1=80=E5=B1=9E=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/runtime/content/utils.test.ts | 9 +++++++-- src/runtime/content/utils.ts | 15 +++++++++++++-- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/runtime/content/utils.test.ts b/src/runtime/content/utils.test.ts index 6bbefb40..35baa125 100644 --- a/src/runtime/content/utils.test.ts +++ b/src/runtime/content/utils.test.ts @@ -9,9 +9,10 @@ describe("proxy context", () => { console.log("eval"); }, addEventListener: () => {}, + location: "ok", }; init.set("onload", true); - init.set("gbok", true); + init.set("location", true); const _this = proxyContext(global, context); it("set contenxt", () => { @@ -35,13 +36,17 @@ describe("proxy context", () => { expect(global["okk"]).toEqual(undefined); }); - it("访问global的对象", () => { + it("禁止穿透global对象", () => { expect(_this["gbok"]).toBeUndefined(); }); it("禁止修改window", () => { expect(() => (_this["window"] = "ok")).toThrow(); }); + + it("访问location", () => { + expect(_this.location).not.toBeUndefined(); + }); }); // 只允许访问onxxxxx diff --git a/src/runtime/content/utils.ts b/src/runtime/content/utils.ts index 0a35724e..14c84b67 100644 --- a/src/runtime/content/utils.ts +++ b/src/runtime/content/utils.ts @@ -118,7 +118,7 @@ export const writables: { [key: string]: any } = { dispatchEvent: global.dispatchEvent.bind(global), }; -// 记录初始的 +// 记录初始的window字段 export const init = new Map(); // 需要用到全局的 @@ -131,6 +131,7 @@ export const unscopables: { [key: string]: boolean } = { const descs = Object.getOwnPropertyDescriptors(global); Object.keys(descs).forEach((key) => { const desc = descs[key]; + // 可写但不在特殊配置writables中 if (desc && desc.writable && !writables[key]) { if (typeof desc.value === "function") { // 判断是否需要bind,例如Object、Function这些就不需要bind @@ -239,8 +240,8 @@ export function proxyContext( } return special[name]; } - // 只处理onxxxx的事件 if (has(global, name)) { + // 特殊处理onxxxx的事件 if (name.startsWith("on")) { if ( typeof global[name] === "function" && @@ -251,6 +252,16 @@ export function proxyContext( return global[name]; } } + if (init.has(name)) { + const val = global[name]; + if ( + typeof val === "function" && + !(<{ prototype: any }>val).prototype + ) { + return (<{ bind: any }>val).bind(global); + } + return val; + } } else if (name === Symbol.unscopables) { return unscopables; }