Windows UWP - WebView get selected Text

拈花ヽ惹草 提交于 2019-12-13 05:47:19

问题


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

DataPackage package = await webview.CaptureSelectedContentToDataPackageAsync();

and read out the string with

await package.GetView().GetTextAsync();

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.

Any help would be appreciated.

UPDATE1:

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

回答1:


I would use

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

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.

Reference Documentation



来源:https://stackoverflow.com/questions/38511078/windows-uwp-webview-get-selected-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!