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

相关推荐
Frank学习路上1 小时前
【IOS】XCode创建firstapp并运行(成为IOS开发者)
开发语言·学习·ios·cocoa·xcode
瓜子三百克8 小时前
CALayer的异步处理
macos·ios·cocoa
吴Wu涛涛涛涛涛Tao9 小时前
一步到位:用 Very Good CLI × Bloc × go_router 打好 Flutter 工程地基
flutter·ios
@PHARAOH10 小时前
WHAT - 依赖管理工具 CocoaPods
xcode·cocoapods
杂雾无尘11 小时前
开发者必看:如何在 iOS 应用中完美实现动态自定义字体!
ios·swift·apple
kymjs张涛13 小时前
零一开源|前沿技术周报 #6
前端·ios·harmonyos
与火星的孩子对话1 天前
Unity进阶课程【六】Android、ios、Pad 终端设备打包局域网IP调试、USB调试、性能检测、控制台打印日志等、C#
android·unity·ios·c#·ip
小溪彼岸1 天前
【XCode】Copilot for XCode AI编程助手
xcode
恋猫de小郭2 天前
Flutter Widget Preview 功能已合并到 master,提前在体验毛坯的预览支持
android·flutter·ios
点金石游戏出海2 天前
每周资讯 | Krafton斥资750亿日元收购日本动画公司ADK;《崩坏:星穹铁道》新版本首日登顶iOS畅销榜
游戏·ios·业界资讯·apple·崩坏星穹铁道