在iframe /对象代码中运行时更新初始路由器网址

hrp*_*xQ4 6 html javascript node.js express vue.js

目前,我正在容器/主Vue应用的对象标签(iframe也可以工作)内渲染Vue应用。首先,我设置了一个文件服务器,为该容器或请求的子应用程序提供服务,以使其在div中呈现。

为了简单起见,我将仅显示Node / Express服务器所需的路由

// serve the sub-app on demand
router.get('/subApps/:appName', function(req, res) {
    res.sendFile(path.resolve(__dirname, `../apps/${req.params.appName}/index.html`);
});

// always render the app container if no sub-app was requested
router.get('*', function(req, res) {
    res.sendFile(path.resolve(__dirname, '../base/index.html'));
});
Run Code Online (Sandbox Code Playgroud)

我的应用程序容器/主Vue应用程序位于上渲染的视图文件中/apps/:appName,请求该子应用程序并将其包装到对象标签中

  document.getElementById("customAppContainer").innerHTML = `<object style="width: 100%; height:100%;" data="http://localhost:3000/subApps/${appKey}"></object>`;
Run Code Online (Sandbox Code Playgroud)

这种方法可以正常工作,但呈现的子应用程序http://localhost:3000/subApps/app-one虽然应使用url,但仍使用启动URL http://localhost:3000/apps/app-one。当子应用加载路由器实例时,我必须将启动网址从iframe网址更改为浏览器网址(父网址)。

我考虑过用 history.replaceState

const router = new Router({ ... });

router.afterEach((to, from) => {
    localStorage.subAppRouteUpdate = to.path;
});

if (window.location !== window.parent.location) {
    const browserUrl = top.location.href;
    history.replaceState(null, null, browserUrl);
}

export default router;
Run Code Online (Sandbox Code Playgroud)

我为什么要这样做?主应用程序的App.vue应该将子应用程序路由附加到浏览器URL。通过这种方法,可以在子应用程序内部导航时更新浏览器网址。我通过将子应用程序URL存储到本地存储并在主应用程序侧监听本地存储更改来实现此目的。因此App.vue文件使用此代码

<script>
export default {
  created() {
    window.addEventListener("storage", () => {
      const fullRoute = this.$router.currentRoute.fullPath;
      const routeSegments = fullRoute.split("/");
      const appsIndex = routeSegments.indexOf("apps");
      const newBaseUrlSegments = routeSegments.slice(0, appsIndex + 2);
      const newBaseUrl = newBaseUrlSegments.join("/");
      const subAppRoute = localStorage.subAppRouteUpdate;
      const updatedUrl = newBaseUrl.concat(subAppRoute);
      history.replaceState(null, null, updatedUrl);
    });
  }
};
</script>
Run Code Online (Sandbox Code Playgroud)

在使用IFrame时启用路由。几乎可以用,这就是我得到的

在此处输入图片说明

不幸的是,当调用/子应用程序时,浏览器URL被更新为

http:// localhost:3000 / apps / app-one / apps / app-one

虽然我期待

http:// localhost:3000 / apps / app-one /


再生产:

我创建了一个用于复制/测试的存储库。有人知道什么地方可能出问题或如何修复该网址更新吗?


更新:

我认为发生错误是因为在subApp的router.js中,我正在触发此代码

if (window.location !== window.parent.location) {
    const browserUrl = top.location.href;
    history.replaceState(null, null, browserUrl);
}

router.afterEach((to, from) => {
    console.log({ urlToAppend: to.path });
    localStorage.subAppRouteUpdate = to.path;
});
Run Code Online (Sandbox Code Playgroud)

replaceState函数会将IFrame网址从更新/subApps/app-one为正确的浏览器网址/apps/app-one。不幸的是,这将触发afterEach事件并to.path导致发生,/apps/app-one尽管应该如此/

如果将url作为/apps/app-one/users/createafter,则每个事件/users/create当然应该触发。

但是我不知道如何解决此首次触发的事件。