简体   繁体   English

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

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

I have a WebBrowser control which I use to display dynamically generated html pages with different info, including html links. 我有一个WebBrowser控件,用于显示具有不同信息(包括html链接)的动态生成的html页面。 Pages are loaded using webBrowser.DocumentText. 使用webBrowser.DocumentText加载页面。

If I include a link to an external webpage, eg " https://somesite.com/file.htm " the link works fine, but if I link to a local file, eg "file:///c:\\temp\\file.htm", nothing happens when I click the link. 如果我包含指向外部网页的链接,例如“ https://somesite.com/file.htm ”,则该链接可以正常工作,但是如果我链接到本地​​文件,例如“ file:/// c:\\ temp \\ file.htm”,则单击链接不会发生任何反应。

If I grab the source from the page in the WebBrowser control, save it as an html file and open it in Edge, the link works fine. 如果我从WebBrowser控件的页面中获取源代码,将其另存为html文件并在Edge中打开,则链接可以正常工作。

I've been browsing through a ton of webpages trying to find a solution but no luck, none of them seem to address this specific problem which I find strange, as it would seem like a common problem. 我浏览了无数网页,试图找到解决方案,但是没有运气,它们似乎都没有解决这个我觉得很奇怪的特定问题,因为这似乎是一个常见问题。

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

It would be more helpful if you provided a sample that reproduces the problem you're seeing, but here's one way to do it. 如果您提供了一个可以重现您所遇到的问题的示例,则将更加有用,但这是解决问题的一种方法。

The code below writes two files: start.html , which contains a clickable link to the second file, end.html , which just contains some text. 下面的代码编写了两个文件: start.html ,它包含指向第二个文件end.html的可单击链接, end.html仅仅包含一些文本。

Drop a webbrowser control onto the form and run the code. 将一个Web浏览器控件放到窗体上并运行代码。 The first page will load with a link you can click, and when you click it, the second page loads. 第一页将加载您可以单击的链接,单击该链接时,第二页将加载。

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