javascript 如何获取整个文档的文本内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4233490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:44:55  来源:igfitidea点击:

How to get text content of the entire document?

javascriptjquerygoogle-chromegoogle-chrome-extension

提问by artemave

I am building Chrome extension which at some point should determine current page language. In order to do that, my plan is to extract text content of the page (or at least a part of it) and pass it to translation api. However I couldn't find any strait forward way to just get all textNodes of the document.

我正在构建 Chrome 扩展程序,它在某个时候应该确定当前页面语言。为了做到这一点,我的计划是提取页面的文本内容(或至少其中的一部分)并将其传递给翻译 api。但是,我找不到任何方法来获取textNode文档的所有内容。

There is a backup plan which is to recursively analyze $('body').contents()until there is enough text content, but it feels a bit flaky. Perhaps there is a better way?

有个备份方案是递归分析,$('body').contents()直到有足够的文本内容,但感觉有点片面。也许有更好的方法?



Note: Chrome extensions api allows your script to access user page dom as if it was the part of it.

注意:Chrome 扩展 api 允许您的脚本访问用户页面 dom,就好像它是它的一部分一样。

采纳答案by John Hartsock

Using the jQuery text() method

使用jQuery text() 方法

$('body').text()

回答by mortalis

Javascript:

Javascript:

document.body.textContent

回答by pawel

Without jQuery, just as easy: document.body.innerText;

没有 jQuery,同样简单: document.body.innerText;

回答by guerrerocarlos

VanillaJS:

香草JS:

document.body.outerHTML