【问题标题】:How can I replace a window with html as well as change the location at the same time so assets in the html would load correctly?如何用 html 替换窗口并同时更改位置,以便 html 中的资产能够正确加载?
【发布时间】:2019-05-12 03:55:02
【问题描述】:

假设我有一些使用相对路径的预定义资产的 HTML,我将如何在当前页面中加载该 HTML 并同时将窗口位置更改为正确的 URL,以便页面及其所有资产正确加载。

目前如果我使用:

const w = window.open()
w.document.write("<html><body><p>help</p></body></html>")
w.location.replace("http://baseUrl.com")

页面然后呈现 html,然后在替换位置时重新加载,使 document.write 无用。

有没有一种方法可以同时进行,以便 url 和 html 一样加载?

如果我这样做了

const w = window.open()
w.location.replace("http://baseUrl.com")
w.document.write("<html><body><p>help</p></body></html>")

第三行没有运行,因为在替换位置时我无法访问 w 变量。

任何帮助将不胜感激。提前致谢。

【问题讨论】:

    标签: javascript html url query-string webpage


    【解决方案1】:

    您可以在window.replace 中使用查询字符串,如下所示:

    const w = window.open();
    window.location.replace("http://baseUrl.com?data=" + encodeUriComponent("<html><body><p>help</p></body></html>"));
    

    然后在baseUrl.com的文件中:

    var data = decodeUriComponent(window.location.href).split("?")[1];
    document.write(data);
    

    它的作用是将编码的 URI 查询字符串传递到 URL (?data=&lt;html&gt;&lt;body&gt;&lt;p&gt;help&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;),然后接收并解码它,获取末尾的位(HTML)并将其写入文档。希望这会有所帮助!

    【讨论】:

    • 问题是我不拥有baseUrl.com 的文件我从POST 请求中获取内容。
    【解决方案2】:

    我不确定你的目标是否有更好的方法而不是相对 url,但你可以使用&lt;base href='...'&gt; 标签:

    <script type="text/javascript">
        document.head.innerHTML = document.head.innerHTML + "<base href='http://baseUrl.com/' />";
    </script>
    

    基本标签通常需要一个尾随的“/”。

    示例:

    <base href="http://localhost/mywebsite/" />
    

    那么你的 HTML 中的所有 URL 都可以是这样的:

    <img src="images/example.png" />
    <a href="/images/example.png">Link To Image</a>
    

    【讨论】:

    • 我正在考虑做这样的事情......可能会像这样替换 html 字符串:htmlString.replace("&lt;head&gt;", "&lt;head&gt;&lt;base href='baseUrl.com'&gt;")
    【解决方案3】:

    你可以这样做(使用setInterval检测打开的窗口加载,然后写你的帮助信息,url必须是同一个域):

    var w = window.open("http://baseUrl.com")
            var writeAsserts = function () 
            {
                if (w.document.body.childNodes.length > 0) {
                    clearInterval(interval);
                    var div = w.document.createElement("div")
                    div.innerHTML = "<span>help</span>";
                    w.document.body.appendChild(div)
                }
            }
            var interval = setInterval(writeAsserts,10)
    

    【讨论】:

    • 你的意思是 url 必须是同一个域? baseUrl.com 和我的 webapp 将位于不同的域中。不过还是谢谢你的回答!
    • 出于安全原因,您不能跨域修改页面内容。在您的情况下,您可能会在您的网站(同一域)中添加一个包装页面以显示来自 baseUrl.com 的文件。在您的包装页面中,将页面正文分成两部分,一个显示帮助信息,另一个使用 iframe 显示来自 baseUrl.com 的文件,然后您可能可以修改您的帮助信息区域。
    猜你喜欢
    • 2015-05-19
    • 2016-03-19
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    相关资源
    最近更新 更多