【问题标题】:html content in object tags doesn't update the browser url对象标签中的 html 内容不会更新浏览器 url
【发布时间】:2020-02-06 12:53:27
【问题描述】:

我想将 HTML 内容嵌入到 div 中。为了实现这一点,我有一个静态文件服务器为请求的 index.html 文件提供服务。

为了简单和重现,整个代码(路径等)都是硬编码的

首先我的静态文件服务器为基本 index.html 文件和应在基本应用的容器中呈现的子应用提供服务。

const express = require('express');
const path = require('path');
const app = express();
const router = express.Router();

app.use(express.static(__dirname));

router.get('/subApp', function(req, res) {
    res.sendFile(path.join(__dirname, 'subApp.html'));
});

router.get('*', function(req, res) {
    res.sendFile(path.join(__dirname, 'base.html'));
});

app.use('/', router);

app.listen(3000);

基础应用只提供一个请求特定应用的容器。

<div>
  <object style="width: 100%; height:100%;" data="http://localhost:3000/subApp"></object>
</div>

请求的子应用在跳转到某个元素时尝试操作浏览器 url

<a href="#containerTwo">Jump to</a>
<div style="width: 100%;height: 5000px; background:red;">Div One</div>
<div style="width: 100%;height: 100px; background:blue;" id="containerTwo">Div Two</div>

跳转到蓝色容器时,URL 不会改变。但我希望它会在网址中添加#containerTwo。

这可能吗?

我问这个是因为我的真实应用程序嵌入了客户端渲染的 VueJs 应用程序,并且当使用 Vue 路由器浏览子应用程序时,浏览器 URL 永远不会更新。


这个问题的一个可能的解决方案可能是这个答案。它适用于简单的 HTML 文件,但不适用于 Vue 应用程序。

https://stackoverflow.com/a/55209788/9945420

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    对象元素是一种沙盒显示的内容。

    您可以将消息传递给父容器,但它必须接受它。这是否意味着您需要获取从该对象传递的消息并操作父容器 url(检查安全问题,只需在此处使用 '*')

    从子应用发送消息事件:

    <!-- subApp -->
    <a href="#containerTwo" onclick="changeParentUrl(this)">Jump to</a>
    <div style="width: 100%;height: 5000px; background:red;">Div One</div>
    <div style="width: 100%;height: 100px; background:blue;" id="containerTwo">Div Two</div>
    <script>
        function changeParentUrl(link) {
            console.log(link.hash);
            this.parent.postMessage({ hash: link.hash }, '*');
        }
    </script>
    

    然后在您的基础应用中监听该消息事件

    <!-- base app-->
    <object style="width: 100%; height:100%;" data="./subApp.html"></object>
    <script>
        window.addEventListener('message', event => { window.location.hash = event.data.hash });
    </script>
    

    可以查看postMessage API https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

    【讨论】:

    • 感谢您的回复。您知道将 html 文件加载到 div 中的替代方法吗?也许有更好的解决方案:)
    • 嗯在这里找到了一个可行的解决方案stackoverflow.com/a/55209788/9945420 适用于纯 HTML 文件,但不适用于 Vue 应用程序..
    • 您也可以使用 iframe '嵌入' html 文件,但它运行时会遇到相同的通信/沙盒问题。也许,正如您所说的您正在使用 Vue,您可以尝试 componentize 该子应用程序并在主 Vue 组件中使用它。这样,主应用程序和子应用程序都将存在于相同的 HTML 中。我对 Vue 不是很熟悉,但是那里有很多创建应用程序和使用组件的教程scotch.io/tutorials/build-a-to-do-app-with-vue-js-2
    • hm 是的,但是纯 HTML、带有 Jquery 的 HTML、React 和 Angular 也应该可以工作,所以我必须这样做.. :/
    猜你喜欢
    • 2013-01-04
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 2011-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多