0

What's the easiest way to check if a loaded page contains a certain keyword or string? My intent is to execute a function if the text exists anywhere on the page.

The closest thing I've found is:

if (window.location.href.indexOf("my keyword(s)") != -1) {do something}

But this only checks if the URL contains the keyword.

  • Including html tag names? If you want to search the entire source of the document, see this [post](http://stackoverflow.com/questions/817218/get-entire-document-html-as-string). Also, I would look into regular expressions as well. – linstantnoodles Feb 15 '14 at 16:35
  • Not including html tag names, unless the easiest way to do this is to include them. – user2599295 Feb 15 '14 at 16:37
  • So you just want the visible text? – linstantnoodles Feb 15 '14 at 16:45
  • Yes, for this question, that's all I'm inquiring about. But thank you for bringing tag names to my attention. I initially didn't take that into consideration. – user2599295 Feb 15 '14 at 16:49

2 Answers2

0

By using window.document.body.innerText, you get the entire text of the body, without tags.

Giovanni Filardo
  • 1,012
  • 8
  • 14
0

Or this:

if ( !!~document.body.textContent.indexOf("my keyword(s)") 
     || !!~window.location.href.indexOf("my keyword(s)") ) {
    // Keyword found
}
Goran.it
  • 5,991
  • 2
  • 23
  • 25