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

如何修改WebView中长按文本时的可选操作选项

WebView长按文本菜单自定义问题

WebView长按菜单

在WebView中长按文本时,会显示「翻译」「复制」「分享」默认选项,请问如何添加自定义选项或移除现有选项?我推测需要进行原生修改。

补充代码:

@override
Widget build(BuildContext context) {
  return WebViewWidget(
    controller: _controller,
  );
}

解决方案

一、移除默认菜单选项

Android平台

  1. 完全禁用默认菜单:监听长按事件并消费它,阻止默认菜单弹出
_controller.android.setOnLongPressListener((event) async {
  return true; // 返回true表示处理长按事件,不显示默认菜单
});
  1. 关闭特定选项(如翻译):通过WebView设置关闭翻译功能
_controller.android.setSettings((settings) {
  settings.translateEnabled = false;
});

iOS平台

通过自定义上下文菜单配置,只保留需要的选项:

_controller.ios.setContextMenuDelegate(IOSContextMenuDelegate(
  contextMenuConfigurationForElement: (element) async {
    return IOSContextMenuConfiguration(
      menuItems: [
        // 仅保留复制选项
        IOSContextMenuAction(
          title: '复制',
          action: () async => await _controller.copy(),
        ),
      ],
    );
  },
));

二、添加自定义菜单选项

Android平台

监听长按事件后,弹出Flutter自定义弹窗菜单:

_controller.android.setOnLongPressListener((event) async {
  final selectedText = await _controller.getSelectedText();
  if (selectedText != null) {
    showMenu(
      context: context,
      position: RelativeRect.fromLTRB(event.x, event.y, event.x, event.y),
      items: [
        PopupMenuItem(
          child: const Text('自定义操作1'),
          onTap: () {
            // 执行自定义逻辑
          },
        ),
        PopupMenuItem(
          child: const Text('复制'),
          onTap: () => _controller.copy(),
        ),
      ],
    );
  }
  return true;
});

iOS平台

在上下文菜单配置中直接添加自定义选项:

_controller.ios.setContextMenuDelegate(IOSContextMenuDelegate(
  contextMenuConfigurationForElement: (element) async {
    return IOSContextMenuConfiguration(
      menuItems: [
        IOSContextMenuAction(
          title: '复制',
          action: () async => await _controller.copy(),
        ),
        IOSContextMenuAction(
          title: '自定义操作',
          action: () {
            // 执行自定义逻辑
          },
        ),
      ],
    );
  },
));

说明

WebView的长按菜单行为是平台相关的,确实需要针对Android和iOS分别配置。上述方案基于webview_flutter插件封装的API实现,无需直接编写原生代码;如果需要更复杂的自定义样式或逻辑,可通过MethodChannel调用原生代码扩展。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 22:25:20