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

相关推荐
与火星的孩子对话15 小时前
Unity进阶课程【六】Android、ios、Pad 终端设备打包局域网IP调试、USB调试、性能检测、控制台打印日志等、C#
android·unity·ios·c#·ip
小溪彼岸18 小时前
【XCode】Copilot for XCode AI编程助手
xcode
恋猫de小郭2 天前
Flutter Widget Preview 功能已合并到 master,提前在体验毛坯的预览支持
android·flutter·ios
点金石游戏出海2 天前
每周资讯 | Krafton斥资750亿日元收购日本动画公司ADK;《崩坏:星穹铁道》新版本首日登顶iOS畅销榜
游戏·ios·业界资讯·apple·崩坏星穹铁道
旷世奇才李先生2 天前
Swift 安装使用教程
开发语言·ios·swift
90后的晨仔2 天前
Xcode16报错: SDK does not contain 'libarclite' at the path '/Applicati
ios
finger244802 天前
谈一谈iOS线程管理
ios·objective-c
Digitally2 天前
如何将大型视频文件从 iPhone 传输到 PC
ios·iphone
梅名智2 天前
IOS 蓝牙连接
macos·ios·cocoa
美狐美颜sdk2 天前
跨平台直播美颜SDK集成实录:Android/iOS如何适配贴纸功能
android·人工智能·ios·架构·音视频·美颜sdk·第三方美颜sdk