iOS WKWebView 禁止选中文字

0x00 方法一

通过 JavaScript 注入来实现:

NSString *js = @"document.body.style.userSelect = 'none'; document.body.style.webkitUserSelect = 'none';";
WKUserContentController *ctrl = [[WKUserContentController alloc] init];
WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
[ctrl addUserScript:script];
        
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
config.userContentController = ctrl;
        
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
webView.scrollView.minimumZoomScale = 1.0;
webView.scrollView.maximumZoomScale = 1.0;

0x01 方法二

在加载完成后,注入 JS 代码

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        // 注入JavaScript代码来禁用文字选择
        let script = """
            document.body.style.webkitUserSelect = 'none';
            document.body.style.userSelect = 'none';
        """
        webView.evaluateJavaScript(script, completionHandler: nil)
    }

0x03

重写 WKWebView 的 canPerformAction 方法来禁用文字选择和上下文菜单

class NoSelectWebView: WKWebView {
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        // 禁用文字选择和上下文菜单
        if action == #selector(UIResponderStandardEditActions.copy(_:)) ||
           action == #selector(UIResponderStandardEditActions.select(_:)) ||
           action == #selector(UIResponderStandardEditActions.selectAll(_:)) {
            return false
        }
        return super.canPerformAction(action, withSender: sender)
    }
}

相关推荐
Bruce_Liuxiaowei1 天前
基于阿里云百炼大模型Sensevoice-1的语音识别与文本保存工具开发
人工智能·阿里云·语音识别·xcode
wn5311 天前
【浏览器 - Mac实时调试iOS手机浏览器页面】
前端·macos·ios·智能手机·浏览器
小鹿撞出了脑震荡2 天前
Effective Objective-C 2.0 读书笔记—— 方法调配(method swizzling)
ios·objective-c·swift
小鹿撞出了脑震荡2 天前
Effective Objective-C 2.0 读书笔记—— 消息转发
ios·objective-c·swift
一丝晨光3 天前
Cocoa和Cocoa Touch是什么语言写成的?什么是Cocoa?编程语言中什么是框架?为什么苹果公司Cocoa类库有不少NS前缀?Swift编程语言?
macos·ios·objective-c·cocoa·swift·uikit·cocoa touch
{⌐■_■}5 天前
【Validator】自定义字段、结构体补充及自定义验证,go案例讲解ReportError和errors.As在其中的使用
开发语言·golang·xcode
LucianaiB6 天前
字节iOS面试经验分享:HTTP与网络编程
网络·ios·面试
黄油奥特曼6 天前
Flutter解决macbook M芯片Android Studio中不显示IOS真机的问题
flutter·ios·android studio·m芯片
taopi20246 天前
ios打包:uuid与udid
ios·iphone·ipad
小鹿撞出了脑震荡7 天前
Effective Objective-C 2.0 读书笔记——关联对象
开发语言·ios·objective-c