简体   繁体   中英

Windows UWP - WebView get selected Text

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM