Skip to content

Commit 7e9f889

Browse files
committed
refactor(iframe communication): reconstruct iframe communication mode
1 parent fbbb4e6 commit 7e9f889

File tree

6 files changed

+97
-114
lines changed

6 files changed

+97
-114
lines changed

package-lock.json

Lines changed: 2 additions & 37 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@
2929
"@commitlint/config-conventional": "^16.0.0",
3030
"@conflux-dev/conflux-address-js": "^1.3.12",
3131
"abi-util-lite": "^0.1.0",
32-
"axios": "^0.25.0",
3332
"big.js": "^5.2.2",
3433
"commander": "^8.0.0",
3534
"conventional-changelog-cli": "^2.2.2",

src/interface/provider.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,3 +85,9 @@ export interface IIframeOptions {
8585
| 'importAccount'
8686
waitResult?: boolean
8787
}
88+
89+
export interface IIframeData {
90+
type: 'event' | 'callback' | 'router' | 'default'
91+
data: unknown
92+
success?: boolean
93+
}

src/provider.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -174,14 +174,15 @@ export class Provider implements IProvider {
174174
params: params ? JSON.stringify(paramsObj) : '',
175175
authType:
176176
params && Object.keys(paramsObj).includes('to') && paramsObj['to']
177-
? getAddressType(paramsObj['to']) === AddressType.CONTRACT
177+
? getAddressType(paramsObj['to'] as string) ===
178+
AddressType.CONTRACT
178179
? 'callContract'
179180
: 'createTransaction'
180181
: 'createContract',
181182
})
182183
} catch (e) {
183184
console.error('Error to sendTransaction', e)
184-
return 'fail'
185+
return e
185186
}
186187
case 'anyweb_importAccount':
187188
try {
@@ -193,7 +194,7 @@ export class Provider implements IProvider {
193194
})
194195
} catch (e) {
195196
console.error('Error to import Address', e)
196-
return 'fail'
197+
return e
197198
}
198199
case 'anyweb_version':
199200
return config.version
@@ -209,7 +210,7 @@ export class Provider implements IProvider {
209210
waitResult: false,
210211
})
211212
default:
212-
return 'default'
213+
return 'Unsupported method'
213214
}
214215
}
215216

src/utils/common.ts

Lines changed: 84 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,8 @@
33
* @since 2022/2/11
44
*/
55
import * as forge from 'node-forge'
6-
import axios from 'axios'
7-
import { API_BASE_URL, BASE_URL } from '../config'
8-
import { IAuthResult, IIframeOptions } from '../interface/provider'
6+
import { BASE_URL } from '../config'
7+
import { IAuthResult, IIframeData, IIframeOptions } from '../interface/provider'
98
import { Provider } from '../provider'
109

1110
export const getFrameWidth = () => {
@@ -68,10 +67,38 @@ const setBodyScrollable = () => {
6867
})
6968
}
7069

70+
export const isObject = (obj: unknown) => {
71+
return Object.prototype.toString.call(obj) === '[object Object]'
72+
}
73+
7174
const closeIframe = (root: HTMLDivElement) => {
7275
setBodyScrollable()
7376
root.style.display = 'none'
7477
}
78+
export const sendMessageToApp = ({
79+
data,
80+
type,
81+
success = true,
82+
}: IIframeData) => {
83+
const iframe: HTMLIFrameElement | null = document.getElementById(
84+
'anyweb-iframe'
85+
) as HTMLIFrameElement | null
86+
if (!iframe) {
87+
return
88+
}
89+
iframe.contentWindow &&
90+
iframe.contentWindow.postMessage(
91+
{
92+
data: {
93+
data,
94+
type,
95+
success,
96+
},
97+
type: 'anyweb',
98+
},
99+
'*'
100+
)
101+
}
75102

76103
export const getIframe = async (
77104
url: string,
@@ -82,8 +109,13 @@ export const getIframe = async (
82109
document.getElementById('anyweb-iframe')
83110
) {
84111
const mask = document.getElementById('anyweb-iframe-mask') as HTMLDivElement
85-
const iframe = document.getElementById('anyweb-iframe') as HTMLIFrameElement
86-
iframe.setAttribute('src', url)
112+
sendMessageToApp({
113+
type: 'router',
114+
data: {
115+
path: `/${url}`,
116+
mode: 'redirectTo',
117+
},
118+
})
87119
mask.style.display = 'block'
88120
setBodyNonScrollable()
89121
return () => {
@@ -168,7 +200,7 @@ export const getIframe = async (
168200
iframe.id = 'anyweb-iframe'
169201
mask.id = 'anyweb-iframe-mask'
170202

171-
iframe.setAttribute('src', url)
203+
iframe.setAttribute('src', `${BASE_URL}${url}`)
172204
iframe.setAttribute('frameborder', '0')
173205
iframe.setAttribute('scrolling', 'no')
174206

@@ -200,25 +232,11 @@ export const callIframe = async (
200232
waitResult = true,
201233
}: IIframeOptions
202234
) => {
203-
let serialNumber = ''
204-
const hash = sha512(JSON.stringify({ appId, params }))
205-
206-
try {
207-
serialNumber = (
208-
await axios.post(`${API_BASE_URL}/open/serial/create`, {
209-
hash: hash,
210-
})
211-
).data.data.serialNumber
212-
} catch (e) {
213-
console.error('Get serialNumber error', e)
214-
throw new Error('Get serialNumber error')
215-
}
216-
217235
if (waitResult) {
218236
return new Promise<unknown>(async (resolve, reject) => {
219-
let timer: NodeJS.Timeout | undefined = undefined
237+
let callback: IIframeData | undefined = undefined
220238
const close = await getIframe(
221-
`${BASE_URL}${path}?appId=${appId}&authType=${authType}&serialNumber=${serialNumber}&hash=${hash}&random=${Math.floor(
239+
`${path}?appId=${appId}&authType=${authType}&random=${Math.floor(
222240
Math.random() * 1000
223241
)}&chainId=${chainId}&params=${params}&scope=${JSON.stringify(scope)}`,
224242
() => {
@@ -227,48 +245,54 @@ export const callIframe = async (
227245
}
228246
}
229247
)
230-
const delay = 1000
231-
const next = (i: number) => {
232-
timer = setTimeout(async () => {
233-
let data
234-
try {
235-
data = (
236-
await axios.post(`${API_BASE_URL}/open/serial/read`, {
237-
serialNumber: serialNumber,
238-
hash: hash,
239-
})
240-
).data.data
241-
} catch (e) {
242-
console.error("Can't get result from iframe", e)
243-
next(i++)
244-
return
245-
// reject(new Error("Can't get result from iframe"))
246-
}
247-
if (data && data !== 'false' && data !== false) {
248-
timer && clearTimeout(timer)
249-
close()
250-
resolve(JSON.parse(data))
251-
} else {
252-
if (i * delay > 10 * 60 * 1000) {
253-
close()
254-
reject(new Error('Timeout'))
248+
const timer = setTimeout(() => {
249+
close()
250+
reject(new Error('Timeout'))
251+
}, 10 * 60 * 1000)
252+
253+
// Set Listeners
254+
window.addEventListener(
255+
'message',
256+
function receiveMessageFromIframePage(event) {
257+
if (
258+
event.data &&
259+
isObject(event.data) &&
260+
'type' in event.data &&
261+
event.data.type === 'anyweb'
262+
) {
263+
console.log('SDK收到子页面信息: ', event.data)
264+
callback = event.data.data as IIframeData
265+
266+
if (callback.type === 'callback') {
267+
window.removeEventListener(
268+
'message',
269+
receiveMessageFromIframePage
270+
)
271+
clearTimeout(timer)
272+
if (callback.success) {
273+
close()
274+
resolve(callback.data)
275+
} else {
276+
close()
277+
reject(new Error(callback.data as string))
278+
}
255279
}
256-
next(i++)
257280
}
258-
}, delay)
259-
}
260-
next(0)
281+
},
282+
false
283+
)
261284
})
285+
} else {
286+
await getIframe(
287+
`${path}?appId=${appId}&authType=${authType}&random=${Math.floor(
288+
Math.random() * 1000
289+
)}&chainId=${chainId}&params=${params}&scope=${JSON.stringify(scope)}`,
290+
() => {
291+
return
292+
}
293+
)
294+
return 'ok'
262295
}
263-
await getIframe(
264-
`${BASE_URL}${path}?appId=${appId}&authType=${authType}&serialNumber=${serialNumber}&hash=${hash}&random=${Math.floor(
265-
Math.random() * 1000
266-
)}&chainId=${chainId}&params=${params}&scope=${JSON.stringify(scope)}`,
267-
() => {
268-
return
269-
}
270-
)
271-
return 'ok'
272296
}
273297

274298
export const readCache = (provider: Provider) => {

yarn.lock

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2310,13 +2310,6 @@
23102310
"resolved" "https://registry.npmmirror.com/atob/download/atob-2.1.2.tgz"
23112311
"version" "2.1.2"
23122312

2313-
"axios@^0.25.0":
2314-
"integrity" "sha512-cD8FOb0tRH3uuEe6+evtAbgJtfxr7ly3fQjYcMcuPlgkwVS9xboaVIpcDV+cYQe+yGykgwZCs1pzjntcGa6l5g=="
2315-
"resolved" "https://registry.npmmirror.com/axios/-/axios-0.25.0.tgz"
2316-
"version" "0.25.0"
2317-
dependencies:
2318-
"follow-redirects" "^1.14.7"
2319-
23202313
"babel-jest@^27.4.6":
23212314
"version" "26.6.3"
23222315
dependencies:
@@ -4470,11 +4463,6 @@
44704463
"resolved" "https://registry.npmmirror.com/flatted/download/flatted-3.2.4.tgz?cache=0&sync_timestamp=1636473899515&other_urls=https%3A%2F%2Fregistry.npmmirror.com%2Fflatted%2Fdownload%2Fflatted-3.2.4.tgz"
44714464
"version" "3.2.4"
44724465

4473-
"follow-redirects@^1.14.7":
4474-
"integrity" "sha512-1x0S9UVJHsQprFcEC/qnNzBLcIxsjAV905f/UkQxbclCsoTWlacCNOpQa/anodLl2uaEKFhfWOvM2Qg77+15zA=="
4475-
"resolved" "https://registry.npmmirror.com/follow-redirects/-/follow-redirects-1.14.8.tgz"
4476-
"version" "1.14.8"
4477-
44784466
"for-in@^1.0.2":
44794467
"integrity" "sha1-gQaNKVqBQuwKxybG4iAMMPttXoA="
44804468
"resolved" "https://registry.npmmirror.com/for-in/download/for-in-1.0.2.tgz"

0 commit comments

Comments
 (0)