在 Chrome 中使用 window.open 打开本地 HTML 文件

问题描述 投票:0回答:4

我想通过 Javascript 打开本地 HTML 文件,使用:

window.open ("file://C:/Users/wins/Desktop/exclusiveWordpress.html","mywindow");

但是它会打开一个带有空白页面的新窗口,就像我们过去在未指定 URL 时得到的那样。我如何实现这一目标?

javascript
4个回答
5
投票

这对我来说很好:

文件1:

    <html>
    <head></head>
    <body>
        <a href="#" onclick="window.open('file:///D:/Examples/file2.html'); return false">CLICK ME</a>
    </body>
    <footer></footer>
    </html>

文件2:

    <html>
        ...
    </html>

无论这两个文件是否在同一目录中,此方法都有效,但两个文件必须是本地的。

出于明显的安全原因,如果文件 1 位于远程服务器上,您绝对不能在某些客户端的主机上打开文件,并且尝试这样做将打开一个空白目标。


1
投票

window.location.href = 'file://///fileserver/upload/Old_Upload/05_06_2019/THRESHOLD/BBH/Look/chrs/Delia';

没有什么对我有用。


0
投票

这是适合我的用例的解决方案。我需要在新选项卡中打开本地 HTML 页面,如下所示:

window.open("http://localhost:5173/newPage/newPage.html", "_blank");

但是当然,一旦我部署到生产服务器,这将不起作用。我的解决方案是使用

window.location.hostname
获取域名,然后将其插入 URL:

let domainName = window.location.hostname;

window.open(`http://${domainName}:5173/page/page.html`, "_blank");

-4
投票

首先,确保源页面和目标页面均通过

file
URI 方案提供服务。您无法强制
http
页面打开
file
页面(但反之亦然)。

接下来,调用

window.open()
的脚本应该由用户启动的事件(例如单击、按键等)调用。 仅仅拨打
window.open()
是行不通的。

您可以在此问题页面中进行测试。在 Chrome 的 JavaScript 控制台中运行这些:

// Does nothing
window.open('http://google.com');

// Click anywhere within this page and the new window opens
$(document.body).unbind('click').click(function() { window.open('http://google.com'); });

// This will open a new window, but it would be blank
$(document.body).unbind('click').click(function() { window.open('file:///path/to/a/local/html/file.html'); });

您还可以测试这是否适用于本地文件。 这是一个简单加载 jQuery 的 HTML 文件示例:

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
    </head>
    <body>
        <h5>Feel the presha</h5>
        <h3>Come play my game, I'll test ya</h3>
        <h1>Psycho- somatic- addict- insane!</h1>
    </body>
</html>

然后打开 Chrome 的 JavaScript 控制台并运行上面的语句。第三个现在可以工作了。

© www.soinside.com 2019 - 2024. All rights reserved.