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

相关推荐
奶糖的次元空间4 小时前
iOS 学习笔记 - SwiftUI 和 简单布局
ios·swift
zhensherlock9 小时前
Protocol Launcher 系列:App Store 精准引流与应用推广
javascript·macos·ios·typescript·iphone·mac·ipad
for_ever_love__13 小时前
Objective-C学习 NSDictionary,NSMutableDictionary 功能详解
开发语言·学习·ios·objective-c
for_ever_love__13 小时前
Objective-C学习 协议和委托
开发语言·学习·ios·objective-c
2501_915909061 天前
不用越狱就看不到 iOS App 内部文件?使用 Keymob 查看和导出应用数据目录
android·ios·小程序·https·uni-app·iphone·webview
@大迁世界1 天前
液态玻璃屏正在侵蚀你的电池
macos·ios·objective-c·cocoa
pop_xiaoli1 天前
【iOS】类与对象底层
macos·ios·objective-c·cocoa·xcode
sp42a1 天前
NativeScript iOS 平台开发技巧
ios·nativescript·app 开发
2501_915921431 天前
常用iOS性能测试工具大全及使用指南
android·测试工具·ios·小程序·uni-app·cocoa·iphone
for_ever_love__1 天前
Objecgtive-C学习实例对象,类对象, 元类对象与 isa指针
c语言·学习·ios