Windows UWP - WebView get selected Text

2019-09-10 06:37发布

问题:

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