强制从 Cocoa WebView 进行纯文本复制

发布于 2024-12-06 10:26:14 字数 220 浏览 0 评论 0原文

我有一个 Cocoa Webview 子类,我需要将从它复制的所有文本都变成纯文本。我尝试过覆盖 -copy 和 -pasteboardTypesForSelection,但没有运气,并且调试代码似乎表明这些方法从未被调用。我还尝试在 css 中将 -webkit-user-modify 设置为 read-write-plaintext-only (这在这种情况下也有效),但这似乎没有效果。

有什么想法吗?

I 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

只涨不跌 2024-12-13 10:26:14

好吧,这似乎可行(使用子类实例作为其自己的编辑委托):

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

不确定这是否是最好的方法。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文