【问题标题】:How to disable Copy and Paste (callout/popup) in WKWebView?如何在 WKWebView 中禁用复制和粘贴(标注/弹出)?
【发布时间】:2021-06-22 05:49:41
【问题描述】:

我想禁用标注菜单,如果你在网页视图中长按一个元素就会弹出该菜单:

那里有很多答案,例如this one,但它们似乎都不起作用。不知道UIWebView的东西对WKWebView是否也有效...

我尝试通过 JavaScript 操作 CSS。这似乎只有在您将脚本添加到 WKUserContentController 而不是 didFinish() 时才有效。

不起作用的东西:

window.getSelection().removeAllRanges();
document.body.style.webkitTouchCallout='none';
document.body.style.webkitUserSelect='none';

部分有效的东西:

var style = document.createElement('style');
style.innerHTML = '* { -webkit-touch-callout: none; -webkit-user-select: none; }';
document.getElementsByTagName('head')[0].appendChild(style);

或以 CSS 形式

*:not(input):not(textarea) {
    -webkit-user-select: none;    /* disable selection/copy of UIWebView */
    -webkit-touch-callout: none;  /* disable the iOS popup when long-press on a link */
}

只有**:not(input):not(textarea) 之类的东西似乎有效(没有body 或其他特定标签)。这样做的问题是,这么多元素被禁用了……我只需要在某些特定元素上使用它!

我也试过用canPerformAction()

private static readonly Selector copyAction = new Selector("copy:");
private static readonly Selector pasteAction = new Selector("paste:");
private static readonly Selector cutAction = new Selector("cut:");

public override bool CanPerform(Selector action, NSObject withSender)
{
    if (action == copyAction || action == pasteAction || action == cutAction)
    {
        System.Diagnostics.Debug.WriteLine(action.Name);
    }

    return false;
}

这里似乎链中的另一个响应者正在返回 true 并覆盖我的设置。弹出/标注菜单仍然出现。我只是尽量减少可用选项(如上图所示)。

我唯一可以尝试的是使用手势识别器来禁用此类点击,但目前我不知道如何。

如何禁用弹出/标注菜单?

【问题讨论】:

  • 尝试在 Safari 中打开 webview 检查问题是否仍然存在。您也可以分享示例,以便我可以在我身边进行测试。
  • 好的,我会做一些测试,如果我发现了什么,我会告诉你的。您需要哪种样品? Xamarin 一个、网页还是两者兼而有之?我真的不能给你网页,但你可以试试this link,然后用 iPhone (iOS 14) 设备长按“操作”按钮。这应该模拟问题。

标签: javascript css ios xamarin.ios wkwebview


【解决方案1】:

我已经尝试覆盖在 UIWebView 中运行良好的方法 canPerformAction,但它在 WKWebView 上不起作用。

    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
    if action == #selector(UIResponderStandardEditActions.cut(_:)) ||
        action == #selector(UIResponderStandardEditActions.copy(_:)) ||
        action == #selector(UIResponderStandardEditActions.selectAll(_:)) ||
        action == #selector(UIResponderStandardEditActions.select(_:)) {
        return false
    }
    return super.canPerformAction(action, withSender: sender)
}

【讨论】:

    猜你喜欢
    • 2011-10-04
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    • 2019-09-24
    • 1970-01-01
    相关资源
    最近更新 更多