禁用Webview中的剪切/复制



好吧,场景很简单:

  • 我有一个WebView
  • 我希望用户不能够从该网络视图中剪切/复制任何内容,无论是什么(使用C,还是通过编辑菜单)

我知道我必须对WebView进行子类化,但我必须覆盖哪些特定的方法?

有什么想法吗?(欢迎任何其他方法!)

将以下CSS添加到某个文件

html {
    -ms-touch-action: manipulation;
    touch-action: manipulation;
}
body {
    -webkit-user-select: none !important;
    -webkit-tap-highlight-color: rgba(0,0,0,0) !important;
    -webkit-touch-callout: none !important;
}  

并将该CSS链接到您的HTML

<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <link rel="stylesheet" href="LayoutTemplates/css/style.css" type="text/css" />
    </head>
</html>  

或者通过程序禁用

- (void)webViewDidFinishLoad:(UIWebView *)webView 
{
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
}

好吧,这是解决方案。

首先,设置Webview的编辑代理:

[_myWebview setEditingDelegate:self];

然后实现我们需要的一个功能,以拦截复制/剪切操作(或任何相关操作,但这是我们无论如何都要做的):

- (BOOL)webView:(WebView *)webView doCommandBySelector:(SEL)command
{
    NSString* commandStr = NSStringFromSelector(command);
    if ( ([commandStr isEqualToString:@"copy:"]) || 
         ([commandStr isEqualToString:@"cut:"]))
    {
        NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
        [pasteboard clearContents];
        return YES; // YES as in "Yes, I've handled the command, 
                    // = don't do anything else" :-)
    }
    else return NO;
}

我希望你不要像我那样浪费时间去寻找一个有效的答案…:-)

最新更新