Disable Cut / Copy in Webview

OK, the script is simple:

  • I have a WebView
  • I want to prevent the user from being able to cut / copy anything from this web view, no matter what (either with ⌘Cor via the Edit menu)

I know I need to subclass the WebView, but what specific methods do I need to override?

Any ideas? (Any other approach is appreciated!)

+3


source to share


2 answers


Add the following CSS to some file

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

      

And link this CSS to your 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>  

      

Or disable it programmatically

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

      

+3


source


OK, here's the solution.

First, install the Webview edit delegate:

[_myWebview setEditingDelegate:self];

      



Then we implement one function we need to intercept copy / cut actions (or any action for that matter, but that's what we're going to do anyway):

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

      

I hope you don't waste as much time as I was looking for the correct answer ... :-)

+3


source







All Articles