diff --git a/packages/vant-cli/site/common/iframe-router.js b/packages/vant-cli/site/common/iframe-router.js index 5257f2ada..789c2ccc8 100644 --- a/packages/vant-cli/site/common/iframe-router.js +++ b/packages/vant-cli/site/common/iframe-router.js @@ -2,7 +2,28 @@ * 同步父窗口和 iframe 的 vue-router 状态 */ -import { iframeReady } from '.'; +let queue = []; +let isIframeReady = false; + +function iframeReady(callback) { + if (isIframeReady) { + callback(); + } else { + queue.push(callback); + } +} + +if (window.top === window) { + window.addEventListener('message', (event) => { + if (event.data.type === 'iframeReady') { + isIframeReady = true; + queue.forEach((callback) => callback()); + queue = []; + } + }); +} else { + window.top.postMessage({ type: 'iframeReady' }, '*'); +} function getCurrentDir() { const router = window.vueRouter; @@ -22,8 +43,8 @@ export function syncPathToParent() { export function syncPathToChild() { const iframe = document.querySelector('iframe'); if (iframe) { - iframeReady(iframe, () => { - iframe.postMessage( + iframeReady(() => { + iframe.contentWindow.postMessage( { type: 'replacePath', value: getCurrentDir(), @@ -36,7 +57,11 @@ export function syncPathToChild() { export function listenToSyncPath(router) { window.addEventListener('message', (event) => { - const path = event.data || ''; + if (event.data?.type !== 'replacePath') { + return; + } + + const path = event.data?.value || ''; // should preserve hash for anchor if (router.currentRoute.value.path !== path) { router.replace(path).catch(() => {}); diff --git a/packages/vant-cli/site/common/index.js b/packages/vant-cli/site/common/index.js index 6cf96dab9..0da499ee8 100644 --- a/packages/vant-cli/site/common/index.js +++ b/packages/vant-cli/site/common/index.js @@ -1,20 +1,3 @@ -function iframeReady(iframe, callback) { - const doc = iframe.contentDocument || iframe.contentWindow.document; - const interval = () => { - if (iframe.contentWindow.replacePath) { - callback(); - } else { - setTimeout(interval, 50); - } - }; - - if (doc.readyState === 'complete') { - interval(); - } else { - iframe.onload = interval; - } -} - const ua = navigator.userAgent.toLowerCase(); const isMobile = /ios|iphone|ipod|ipad|android/.test(ua); @@ -25,4 +8,4 @@ export function decamelize(str, sep = '-') { .toLowerCase(); } -export { isMobile, iframeReady }; +export { isMobile };