Skip to content

Commit

Permalink
🐛 处理全局属性
Browse files Browse the repository at this point in the history
  • Loading branch information
CodFrm committed Apr 29, 2024
1 parent 577f7e5 commit ff3b721
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
9 changes: 7 additions & 2 deletions src/runtime/content/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand All @@ -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
Expand Down
15 changes: 13 additions & 2 deletions src/runtime/content/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ export const writables: { [key: string]: any } = {
dispatchEvent: global.dispatchEvent.bind(global),
};

// 记录初始的
// 记录初始的window字段
export const init = new Map<string, boolean>();

// 需要用到全局的
Expand All @@ -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
Expand Down Expand Up @@ -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" &&
Expand All @@ -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;
}
Expand Down

0 comments on commit ff3b721

Please sign in to comment.