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

如何修改JS函数以通用获取当前视口中的所有文本元素?

解决方案

这里有两种通用方案可以实现你的需求,不用逐个列举文本标签,直接适配不同页面的文本元素类型:


方法1:基于文本节点的精准获取

这种方法直接遍历页面中所有文本节点,过滤空白内容后,检查其所属元素是否在视口中,能覆盖所有类型的文本承载元素(包括h1、span、div甚至自定义标签)。

修改后的函数代码:

async function getVisibleText() {
  let visibleText = '';
  const windowHeight = window.innerHeight || document.documentElement.clientHeight;

  // 递归遍历所有文本节点
  function traverseTextNodes(node) {
    if (node.nodeType === Node.TEXT_NODE) {
      const text = node.textContent.trim();
      if (text) {
        const parentElement = node.parentElement;
        const rect = parentElement.getBoundingClientRect();
        // 判断元素是否与视口有交集
        const isVisible = rect.top < windowHeight && rect.bottom > 0;
        if (isVisible) {
          visibleText += text + ' ';
        }
      }
    } else {
      // 跳过脚本、样式等非展示性元素
      const skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'IFRAME', 'OBJECT', 'EMBED'];
      if (!skipTags.includes(node.tagName)) {
        node.childNodes.forEach(traverseTextNodes);
      }
    }
  }

  traverseTextNodes(document.body);
  return visibleText.trim();
}

优势:

  • 完全通用,不受页面文本标签类型限制
  • 只提取有实际内容的文本,自动过滤空白节点
  • 排除了脚本、样式等非用户可见的文本内容

方法2:基于CSS选择器的批量获取

如果不想用递归处理节点,可以通过CSS选择器批量排除非文本元素,再过滤可见元素,代码更简洁:

async function getVisibleText() {
  let visibleText = '';
  const windowHeight = window.innerHeight || document.documentElement.clientHeight;

  // 获取所有非脚本/样式类的元素
  const elements = Array.from(document.body.querySelectorAll(':not(script):not(style):not(noscript):not(iframe):not(object):not(embed)'));
  
  elements.forEach(el => {
    const rect = el.getBoundingClientRect();
    const isVisible = rect.top < windowHeight && rect.bottom > 0;
    if (isVisible) {
      const text = el.innerText.trim();
      if (text) {
        visibleText += text + ' ';
      }
    }
  });

  return visibleText.trim();
}

优势:

  • 代码结构简单,无需递归逻辑
  • 可根据需求快速调整排除的元素类型

注意:

  • 部分嵌套元素可能会重复提取文本,但innerText会自动处理换行和空白,对结果影响不大
  • 如果页面有自定义的非文本展示元素,可自行添加到选择器的排除列表中

通用优化说明

  1. 简化可见性判断:将原条件简化为rect.top < windowHeight && rect.bottom > 0,只要元素有一部分在视口内就判定为可见,更符合实际场景
  2. 缓存视口高度:避免重复获取window.innerHeight或document.documentElement.clientHeight,提升性能
  3. 过滤空白文本:自动剔除无意义的空白内容,避免拼接无效字符串

你可以直接把上述代码复制到浏览器控制台运行,返回结果即为当前视口中所有可见文本的拼接内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 09:55:20