开发者

Force plaintext copy from a Cocoa WebView

开发者 https://www.devze.com 2023-04-07 21:37 出处:网络
I开发者_JS百科 have a Cocoa Webview subclass, and I need to make all text copied from it be plaintext only. I have tried overriding -copy and -pasteboardTypesForSelection, but no luck, and debugging c

I开发者_JS百科 have a Cocoa Webview subclass, and I need to make all text copied from it be plaintext only. I have tried overriding -copy and -pasteboardTypesForSelection, but no luck, and debugging code seems to indicate that those methods are never called. I've also tried setting -webkit-user-modify to read-write-plaintext-only in the css (this would also work in this situation) but that seemed to have no effect.

Any ideas?


Okay this seems to work (with the subclass instance as its own editing delegate):

- (BOOL)webView:(WebView *)webView doCommandBySelector:(SEL)command
{
    if (command == @selector(copy:)) {
        NSString *markup = [[self selectedDOMRange] markupString];
        NSData *data = [markup dataUsingEncoding: NSUTF8StringEncoding];
        NSNumber *n = [NSNumber numberWithUnsignedInteger: NSUTF8StringEncoding];
        NSDictionary *options = [NSDictionary dictionaryWithObject:n forKey: NSCharacterEncodingDocumentOption];
        NSAttributedString *as = [[NSAttributedString alloc] initWithHTML:data options:options documentAttributes: NULL];
        NSString *selectedString = [as string];
        [as autorelease];

        NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
        [pasteboard clearContents];
        NSArray *objectsToCopy = [NSArray arrayWithObject: selectedString];
        [pasteboard writeObjects:objectsToCopy];
        return YES;
    }
    return NO;
}

Not sure if this is the best way.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号