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

相关推荐
清晨細雨40 分钟前
UniApp集成极光推送详细教程
android·ios·uni-app·极光推送
ii_best5 小时前
iOS 按键越狱脚本支持一键新机软件教程
ios
lilili啊啊啊7 小时前
查看iphone手机的使用记录-克魔实战
ios·智能手机·iphone
鸿蒙布道师8 小时前
鸿蒙NEXT开发随机工具类(ArkTs)
android·ios·华为·harmonyos·arkts·鸿蒙系统·huawei
1024小神9 小时前
theos工具来编译xcode的swiftUI项目为ipa文件
macos·swiftui·xcode
watersink19 小时前
基于大模型的pc版语音对话问答
ide·macos·xcode
Python之栈20 小时前
Python 3.13 正式支持 iOS:移动开发的新篇章
python·macos·objective-c·cocoa
鸿蒙布道师21 小时前
鸿蒙NEXT开发Base64工具类(ArkTs)
android·ios·华为·harmonyos·arkts·鸿蒙系统·huawei
美狐美颜sdk1 天前
美颜SDK兼容性挑战:如何让美颜滤镜API适配iOS与安卓?
android·深度学习·ios·美颜sdk·第三方美颜sdk·视频美颜sdk
Invisible_He1 天前
iOS自定义collection view的page size(width/height)分页效果
ui·ios·swift·collection