【问题标题】:(Android & iOS) Xamarin - How to get tapped/selected text or paragraph from a WebView?(Android 和 iOS)Xamarin - 如何从 WebView 中获取点击/选定的文本或段落?
【发布时间】:2019-11-26 12:03:53
【问题描述】:

如何从 WebView 中获取选定的文本范围?是否有诸如 selectedSomething 之类的 WebView 自定义事件?

--

如果没有解决办法;

我可以从 Webview 获取复制的文本/段落吗?复制的是否有事件(可能是自定义的)?

--

我很乐意提供任何帮助。

【问题讨论】:

  • 对于 iOS,您可以查看 this thread 关于从 uiwebview 获取选定文本。
  • 我可以在本机代码中看到一些解决方案,但是在 c# 中等效的代码是什么?
  • 通常,如果您在本机代码中找到解决方案,您可以使用 custom-rendererdependency-service 在 Xamarin.forms 中实现。 WebView有一个叫EvaluateJavaScriptAsync的方法,你可以试试。
  • 感谢您抽出宝贵时间,杰克!您能否提供有关该过程的示例代码?机制如何从 WebView 返回值?我应该在选定文本后单击一个按钮吗?如果我必须这样做,这不是一个有效的方法。选择文本时如何触发?我无法匹配这个谜题。
  • 我今天下午做了一些测试,我发现当我在webView中选择一些文本时,如果我点击按钮,由于点击事件,被选中的文本将变为未选中。然后我搜索了wknavigationdelegate,似乎选择文本时不会触发任何方法。所以到目前为止我还没有找到解决方案。当我找到东西时,我会更新你。

标签: xamarin.forms webview


【解决方案1】:

选择字符串后,选择会很快消失。该解决方案来自 Xamarin 论坛中的 ColeX。该选择适用于创建自定义渲染器并用 WKWebView 替换默认 webview。

(https://forums.xamarin.com/discussion/comment/396734)

自定义网页视图

public class CustomWebView : WebView
{
    public static readonly BindableProperty UriProperty = BindableProperty.Create(
        propertyName: "Uri",
        returnType: typeof(string),
        declaringType: typeof(CustomWebView),
        defaultValue: default(string));

    public string Uri
    {
        get { return (string)GetValue(UriProperty); }
        set { SetValue(UriProperty, value); }
    }
}

主页

  //xmlns:local ="clr-namespace:App1"
<local:CustomWebView Uri="https://docs.microsoft.com/en-us/xamarin/ios/" HeightRequest="300"/>

自定义渲染器

[assembly: ExportRenderer(typeof(CustomWebView), typeof(HybridWebViewRenderer))]
namespace App1.iOS
{
    class HybridWebViewRenderer : ViewRenderer<CustomWebView, WKWebView>
    {

        protected override void OnElementChanged(ElementChangedEventArgs<CustomWebView> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                var webView = new WKWebView(Frame, new WKWebViewConfiguration());
                SetNativeControl(webView);
            }
            if (e.NewElement != null)
            {
                Control.LoadRequest(new NSUrlRequest(new NSUrl(Element.Uri)));
            }
        }

    }
}

检测Copy事件的事件 将代码放在自定义渲染器或 AppDelegate 中。

 NSNotificationCenter.DefaultCenter.AddObserver(UIPasteboard.ChangedNotification,(noti)=> {
     var s = UIPasteboard.General.String;
     MessagingCenter.Send<object,string>(this, "Hi",s);
  },null);

【讨论】:

    猜你喜欢
    • 2012-03-17
    • 2015-04-02
    • 2014-03-04
    • 2010-11-28
    • 2010-10-25
    • 1970-01-01
    • 2011-01-24
    • 1970-01-01
    • 2012-03-23
    相关资源
    最近更新 更多