【问题标题】:Windows UWP - WebView get selected TextWindows UWP - WebView 获取选定的文本
【发布时间】:2016-11-25 10:48:26
【问题描述】:

目前在我的 UWP 应用程序中,我正在通过文本选择 web 视图

DataPackage package = await webview.CaptureSelectedContentToDataPackageAsync();

并用

读出字符串
await package.GetView().GetTextAsync();

这在 PC 上完美运行,但在手机上却不行。

在电话上解决问题的最佳方式是什么?我尝试用

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

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

任何帮助将不胜感激。

更新1:

修改代码如下,结果还是只能在PC上运行,不能在手机上运行:

  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();
  }

【问题讨论】:

    标签: javascript webview win-universal-app uwp windows-10-universal


    【解决方案1】:

    我会用

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

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

    Reference Documentation

    【讨论】:

    • 实际上我确实使用字符串 string text = await mainwebview1.InvokeScriptAsync("eval", new string[] { "document.getSelection().toString();" });但这又只能在电脑上使用,而不能在手机上使用。有没有cmets?
    • @SunnySonic 老实说我在猜。在没有实际看到您的代码、错误等的情况下,我不知道是否有人能够回答这个问题。我有一个应用程序可以在手机和桌面上广泛使用 webview。
    • 谢谢。用当前代码更新了我的答案。该行为在计算机上运行良好,但在手机上始终为空。
    • @SunnySonic 您确定手机浏览器支持 document.getSelection() 吗?也许您需要在手机上进行不同的 JavaScript 调用?
    • 会不会和这个有关? stackoverflow.com/questions/3538798/…
    猜你喜欢
    • 1970-01-01
    • 2017-06-01
    • 2012-03-17
    • 2015-04-02
    • 2017-07-01
    • 1970-01-01
    • 2018-01-18
    • 2019-11-26
    • 1970-01-01
    相关资源
    最近更新 更多