You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS15中WKWebView如何禁用长按文本选择功能且不影响输入交互?

可行解决方案

方案1:注入CSS实现精准控制文本选中权限(推荐)

该方案只会禁用普通元素的文本选中、长按弹出菜单能力,不会影响输入框、文本域的正常编辑交互,适配iOS15+所有版本。
你需要在初始化WKWebView时向页面注入自定义CSS,原生实现代码如下:

WKWebViewConfiguration* conf = [[WKWebViewConfiguration alloc] init];
// 不要全局关闭textInteractionEnabled,保留默认YES即可
NSString *disableSelectCss = @"*:not(input):not(textarea) { \
  -webkit-user-select: none; \
  user-select: none; \
  -webkit-touch-callout: none; \
} \
input, textarea { \
  -webkit-user-select: auto; \
  user-select: auto; \
}";
// 构造注入CSS的脚本
NSString *jsStr = [NSString stringWithFormat:@"var styleNode = document.createElement('style'); styleNode.innerHTML = `%@`; document.head.appendChild(styleNode);", disableSelectCss];
WKUserScript *userScript = [[WKUserScript alloc] initWithSource:jsStr injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[conf.userContentController addUserScript:userScript];

如果你的Web应用前端代码是可自行修改的,也可以直接把上述CSS代码加到前端全局样式文件中,效果完全一致,不需要原生侧做额外处理。

方案2:额外增加JS事件拦截处理极端场景

如果注入CSS后仍存在长按拖动选中文本的问题,可以额外注入以下JS脚本,拦截非输入区域的长按事件:

NSString *disableLongPressJs = @"document.addEventListener('longpress', function(e) { \
  const allowTags = ['INPUT', 'TEXTAREA']; \
  if (!allowTags.includes(e.target.tagName.toUpperCase())) { \
    e.preventDefault(); \
  } \
}, { passive: false });";
WKUserScript *longPressScript = [[WKUserScript alloc] initWithSource:disableLongPressJs injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[conf.userContentController addUserScript:longPressScript];

注意事项

  • 不要使用全局设置preferences.textInteractionEnabled = false的方案,该属性会禁用所有文本相关交互能力,包括输入框的聚焦、选中、编辑等核心功能,不符合需求
  • 注入脚本时选择WKUserScriptInjectionTimeAtDocumentStart时机,可以保证页面加载初始就生效,避免出现用户刚进入页面时还能选中文本的问题

内容的提问来源于stack exchange,提问作者ALD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 08:54:02