【问题标题】:How to set the url in IHTMLDocument2 without it navigating to a new page如何在 IHTMLDocument2 中设置 url 而不会导航到新页面
【发布时间】:2011-11-18 01:32:24
【问题描述】:

写完htmldocument 后如何设置它的网址。例如:

WebBrowser wb = new WebBrowser();
wb.Navigate(new Uri(location, UriKind.Absolute));
IHTMLDocument2 myDoc = new HTMLDocumentClass();
myDoc.write(new object[] { wb.DocumentText});
myDoc.close();

如果我执行myDoc.url = "http://www.google.com",它会尝试加载谷歌。
如何在不尝试加载该 url 的情况下设置 url?

【问题讨论】:

  • 嗯。如果它不会加载 google,那么您的 HTML 文档对象就会处于不一致的状态。它可能包含一个空的 DOM,或者某个网站的 DOM,但它的 URL 属性会保存 google 的 URL...

标签: url c#-4.0 mshtml ihtmldocument2


【解决方案1】:

这些步骤应该会为您提供一个包含正确 URL 和您自己的内容的文档:

  1. 直接从 URL 创建文档(因此您以后不必设置 URL)
  2. 停止文档下载(因为您不需要该内容)
  3. 用您的内容填写文档

这段代码展示了如何做到这一点:

// 1. Create new document from URL
IHTMLDocument2 NewDoc = (wb.Document as IHTMLDocument4).createDocumentFromUrl("http://www.stackoverflow.com", "null");
// 2. Immediately stop navigating; the URL is still set
NewDoc.execCommand("Stop", false, null);
// 3. Now write your stuff to the document
// ... 

注意:很难猜测在第 1 步和第 2 步之间可以下载多少内容,因为加载是异步进行的。因此,在执行步骤 3 之前检查文档是否确实为空可能会很好。如果不是,请清除文档并继续。

【讨论】:

  • 即使命令紧随其后,它仍然会发出一个 http 请求……即使它被中止了。如果实在没办法,过几天我就接受了。
猜你喜欢
  • 1970-01-01
  • 2014-04-11
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 2020-06-29
  • 2015-01-09
  • 1970-01-01
  • 2021-10-13
相关资源
最近更新 更多