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

相关推荐
游戏开发爱好者89 小时前
iOS IPA 上传工具全面解析,从 Transporter 到开心上架(Appuploader)命令行的高效上架实践
android·ios·小程序·https·uni-app·iphone·webview
denggun1234520 小时前
Xcode的App Thinning Size Report分析包体积
macos·蓝桥杯·xcode
ajassi20001 天前
开源 Objective-C IOS 应用开发(十四)传感器--陀螺仪和gps
ios·开源·objective-c
二流小码农1 天前
鸿蒙开发:支持自定义组件的跑马灯
android·ios·harmonyos
2501_915106321 天前
iOS 抓包全流程指南,HTTPS 抓包、TCP 数据流分析与多工具协同的方法论
android·tcp/ip·ios·小程序·https·uni-app·iphone
3***49961 天前
Swift Experience
开发语言·ios·swift
疯笔码良2 天前
【IOS开发】Objective-C 与 Swift 的对比
ios
枫子有风2 天前
【go.sixue.work】2.2 面向对象:接口与多态
开发语言·后端·golang·xcode
阿斌_bingyu7092 天前
uniapp实现android/IOS消息推送
android·ios·uni-app
QuantumLeap丶2 天前
《Flutter全栈开发实战指南:从零到高级》- 15 -本地数据存储
flutter·ios·dart