从WinRT下的WebView复制内容

我有一个带有一些HTML内容的WebView ,我想将其转换为RTF。 我已经看过那里的RTF转换function,说实话,它们看起来都有点不稳定。 所以我的想法是将WebView内容复制到RichEditBox ,然后从那里保存到RTF。

我已经多次见过这个例子了。

 WebBrowser1.Document.ExecCommand("SelectAll", false, null); WebBrowser1.Document.ExecCommand("Copy", false, null); 

不幸的是,WinRT的WebView控件没有Document属性,所以我不能这样做

有没有办法从控件中提取内容? 要清楚,我想要HTML本身 – 我可以使用它

 InvokeScript("eval", new string[] { "document.getElementById('editor').innerHTML;" }); 

我想要的是实际呈现的 HTML – 就像我在WebView中选择所有内容一样,按CTRL + C然后将其粘贴到wordpad中。

这是我在尝试完成更大任务时要求的一系列问题的一部分 – 在Windowsapp store应用中将HTML转换为RTF。

我很高兴地报告说可以做到以上几点。 我终于弄明白了如何使用DataPackage – 通常用于在应用程序之间共享内容。

首先,这个javascript函数必须存在于webview中加载的HTML中。

 function select_body() { var range = document.body.createTextRange(); range.select(); } 

接下来,您需要using Windows.ApplicationModel.DataTransfer;添加using Windows.ApplicationModel.DataTransfer; 到文档的顶部。 没有足够的StackOverflow答案提到使用的命名空间。 我总是要去找他们。

这是完成魔术的代码:

 // call the select_body function to select the body of our document MyWebView.InvokeScript("select_body", null); // capture a DataPackage object DataPackage p = await MyWebView.CaptureSelectedContentToDataPackageAsync(); // extract the RTF content from the DataPackage string RTF = await p.GetView().GetRtfAsync(); // SetText of the RichEditBox to our RTF string MyRichEditBox.Document.SetText(Windows.UI.Text.TextSetOptions.FormatRtf, RTF); 

我花了大约2个星期试图让它发挥作用。 它最终发现我不必手动将文件编码为RTF。 现在如果我可以让它以相反的方式工作,我会欣喜若狂。 对我正在构建的应用程序不是必不可少的,但这将是一个可爱的function。

UPDATE

回想起来,您可能不需要在HTML中使用该函数,您可能可以使用它(尽管我还没有测试过):

 MyWebView.InvokeScript("execScript", new string[] {"document.body.createTextRange().select();"})