5

I did do some research on google and the userscripts site but was unsuccessful in finding an answer.

So basically how can I check if specific text is found on a page? And the text is in no special tags or anything.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
RayB
  • 2,096
  • 3
  • 24
  • 42

2 Answers2

7

A crude but fast way, for FF GM:

if (/Text you are looking for/i.test (document.body.innerHTML) )
{
    alert ("Found it!");
}

//--- Looking for one of two different texts...
if (/(Text ONE that you are looking for)|(Text TWO that you are looking for)/i.test (document.body.innerHTML) )
{
    alert ("Found one!");
}


For more focused searches use jQuery contains as in this previous question.

Community
  • 1
  • 1
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
  • 1
    `innerHTML` works with Chrome, so that code should work. I only mentioned it because some people get spun up about innerHTML because *writing* to it is problematic on IE. Here we are just scanning it, anyway. – Brock Adams Feb 20 '11 at 22:11
  • @Rayz321, Re: `"Also what would i do if i wanted to search for more than 1 different thing?"`     --- Updated answer to show that concept. – Brock Adams Feb 20 '11 at 23:45
4

for example this script will show if the text specific text is found on this page.

// ==UserScript==
// @name           so5059986
// @namespace      test
// @description    test
// @include        http://stackoverflow.com/questions/5059986/how-to-have-greasemonkey-check-if-text-if-found-on-page
// ==/UserScript==

var xpathResult = document.evaluate("(//text()[contains(., 'specific text')])[1]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
var node=xpathResult.singleNodeValue;
if (node==null)
    alert("text not found");
else
    alert("text found on page");

I don't know what you mean with special tags. Text is always inside some tags.

wimh
  • 15,072
  • 6
  • 47
  • 98
  • I just ment that it was in normal tags and im testing it now – RayB Feb 20 '11 at 21:41
  • Im trying to get it to work to just alert if there is text and it wont seem to work Go ahead and look on http://jsfiddle.net/tQFLz/2/ to see – RayB Feb 20 '11 at 22:11
  • 1
    @Rayz321: There was a syntax error `if (node == null) {};` and the jsFiddle options were not correct for that kind of code. Replace `{};` with `noop;` or just go to http://jsfiddle.net/tQFLz/4/ -- but prepare to be annoyed every 3 seconds. ;) – Brock Adams Feb 20 '11 at 22:56
  • Maybe its just me but it seems to alert even when i remove the text? Oh never mind i got it lol – RayB Feb 20 '11 at 23:06
  • Also what would i do if i wanted to search for more than 1 different thing? – RayB Feb 20 '11 at 23:12