Windows UWP - WebView 获取选定的文本 [英] Windows UWP - WebView get selected Text

查看:28
本文介绍了Windows UWP - WebView 获取选定的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前在我的 UWP 应用中,我正在通过 Web 视图进行文本选择

Currently in my UWP app I am getting the Text-selection of a webview through

DataPackage package = await webview.CaptureSelectedContentToDataPackageAsync();

并用

await package.GetView().GetTextAsync();

这在 PC 上可以完美运行,但在手机上却不能.

This works perfectly on the PC but not on the phone.

通过电话进行处理的最佳方式是什么?我尝试用

What would be the best way to go about it on the phone? I tried injecting javascript with

window.getSelection().toString();  or document.selection.createRange().text;

但它没有用,或者我用错了方法.

but it didn't work or I used it the wrong way.

任何帮助将不胜感激.

更新 1:

将代码更改为以下内容,结果仍然只能在 PC 上运行,而不能在手机上运行:

Changed code to the following with the result that it still only works on the PC but not on the phone:

  string texttoget = await mainwebview1.InvokeScriptAsync("eval", new string[] { "document.getSelection().toString();" });
  if (texttoget != null)
  {
      Debug.WriteLine("Text To get is:    " + texttoget.ToString().Trim());   
  }
  else
  {
        MessageDialog msgbox3 = new MessageDialog("Please select or mark the text you would like to get.");
        await msgbox3.ShowAsync();
  }

推荐答案

我会使用

string text = webview.InvokeScriptAsync("eval", "document.getSelection()");

请记住,在获取选择时您正在浏览器中工作,因此 await package.GetView().GetTextAsync(); 在不同的设备上会变得不稳定.上述方法利用了 javascript,每个设备上的 javascript 应该是相同的.

Remember you're working in a browser at the point of getting the selection so await package.GetView().GetTextAsync(); is going to be wonky on different devices. The above method leverages javascript which should be equal on each device.

参考文档

这篇关于Windows UWP - WebView 获取选定的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆