Skip to content

Commit e3ad1d0

Browse files
committed
improve box seeker to handle origin sandwiches and opener traversal
1 parent 4c117aa commit e3ad1d0

File tree

1 file changed

+41
-19
lines changed

1 file changed

+41
-19
lines changed

packages/scramjet/src/client/client.ts

Lines changed: 41 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,41 @@ export type Trap<T> = {
6161
set?: (ctx: TrapCtx<T>, v: T) => void;
6262
};
6363

64+
function findBox(global: Window, seen: Window[]): SingletonBox | null {
65+
if (seen.includes(global)) return null;
66+
seen.push(global);
67+
68+
try {
69+
if ((SCRAMJETCLIENT in global) as any) {
70+
return global[SCRAMJETCLIENT].box;
71+
}
72+
} catch {}
73+
74+
try {
75+
const b = findBox(global.parent, seen);
76+
if (b) return b;
77+
} catch {}
78+
79+
try {
80+
const b = findBox(global.top, seen);
81+
if (b) return b;
82+
} catch {}
83+
84+
try {
85+
if (global.opener) {
86+
const b = findBox(global.opener, seen);
87+
if (b) return b;
88+
}
89+
} catch {}
90+
91+
for (let i = 0; i < global.length; i++) {
92+
try {
93+
const b = findBox(global[i], seen);
94+
if (b) return b;
95+
} catch {}
96+
}
97+
}
98+
6499
export class ScramjetClient {
65100
locationProxy: any;
66101
serviceWorker: ServiceWorkerContainer;
@@ -96,26 +131,13 @@ export class ScramjetClient {
96131
}
97132

98133
if (iswindow) {
99-
try {
100-
if (SCRAMJETCLIENT in global.parent) {
101-
this.box = global.parent[SCRAMJETCLIENT].box;
102-
}
103-
} catch {}
104-
try {
105-
if (SCRAMJETCLIENT in global.top) {
106-
this.box = global.top[SCRAMJETCLIENT].box;
107-
}
108-
} catch {}
109-
try {
110-
if (global.opener && SCRAMJETCLIENT in global.opener) {
111-
this.box = global.opener[SCRAMJETCLIENT].box;
112-
}
113-
} catch {}
114-
if (!this.box) {
115-
dbg.warn("Creating SingletonBox");
116-
this.box = new SingletonBox(this);
134+
const b = findBox(global as unknown as Window, []);
135+
if (b) {
136+
this.box = b;
117137
}
118-
} else {
138+
}
139+
140+
if (!this.box) {
119141
this.box = new SingletonBox(this);
120142
}
121143

0 commit comments

Comments
 (0)