繁体   English   中英

从WebBrowser中加载的页面中的链接打开本地html文件

[英]Open local html file from link in page loaded in WebBrowser

我有一个WebBrowser控件,用于显示具有不同信息(包括html链接)的动态生成的html页面。 使用webBrowser.DocumentText加载页面。

如果我包含指向外部网页的链接,例如“ https://somesite.com/file.htm ”,则该链接可以正常工作,但是如果我链接到本地​​文件,例如“ file:/// c:\\ temp \\ file.htm”,则单击链接不会发生任何反应。

如果我从WebBrowser控件的页面中获取源代码,将其另存为html文件并在Edge中打开,则链接可以正常工作。

我浏览了无数网页,试图找到解决方案,但是没有运气,它们似乎都没有解决这个我觉得很奇怪的特定问题,因为这似乎是一个常见问题。

   string htmlCode = "<html><body><a href=\"file:///c:\\temp\\testlink.htm\">link</a></body></html>";
        webBrowser1.DocumentText = htmlCode;

如果您提供了一个可以重现您所遇到的问题的示例,则将更加有用,但这是解决问题的一种方法。

下面的代码编写了两个文件: start.html ,它包含指向第二个文件end.html的可单击链接, end.html仅仅包含一些文本。

将一个Web浏览器控件放到窗体上并运行代码。 第一页将加载您可以单击的链接,单击该链接时,第二页将加载。

public Form1()
{
    InitializeComponent();

    // Modify these with paths on your machine
    var startPage = @"f:\private\temp\start.html";
    var endPage = @"f:\private\temp\end.html";

    // This will write the contents of the files above (so they exist)
    File.WriteAllText(startPage, $"<a href=\"file:///{endPage}\">Click Here</a>");
    File.WriteAllText(endPage, "You did it!!");

    // Navigate to the first file so you can click the link
    webBrowser1.Navigate(startPage);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM