javascriptgreasekitfluid-mac-app-engine

If page contains specific text then reload (using javascript)


If the text We are sorry but we made a boo boo appears then

  1. Wait 5 seconds
  2. reload

I would like to do this in JavaScript.

Here is an attempt

(function () {
"use strict";

function walkTheDOM(node, func) {
    if (node && node.nodeType) {
        if (typeof func === "function") {
            func(node);
        }

        node = node.firstChild;
        while (node) {
            walkTheDOM(node, func);
            node = node.nextSibling;
        }
    }
}

function filterElementsByContains(elements, string) {
    var toStringFN = {}.toString,
        text = toStringFN.call(elements),
        result,
        length,
        i,
        element;

    if (text !== "[object NodeList]" && text !== "[object Array]" && !($() instanceof jQuery)) {
        return result;
    }

    result = [];
    if (typeof string === "string") {
        string = new RegExp("^" + string + "$");
    } else if (toStringFN.call(string) !== "[object RegExp]") {
        return result;
    }

    function getText(node) {
        if (node.nodeType === 3) {
            text += node.nodeValue;
        }
    }

    length = elements.length;
    i = 0;
    while (i < length) {
        text = "";
        element = elements[i];
        walkTheDOM(element, getText);
        if (string.test(text)) {
            result.push(element);
        }

        i += 1;
    }

    return result;
}

if(filterElementsByContains([document.getElementsByTagName("table")[0]], /We are sorry but we made a boo boo/).length) {
    location.reload();
}

The above could should, I think, work for the text if it appears in a specific place. I want to make it more general - so that the text could appear anywhere on that page.

Also, I would like to know how to add a pause so that, for example, it waits 5 seconds before reloading.

I guess I would add incorporate something like:

setTimeout(
function() 
{
//location.reload();
}, 5000);

Solution

  • Just do an indexOf on the body's textContent/innerText property

    var content = document.body.textContent || document.body.innerText;
    var hasText = content.indexOf("We are sorry but we made a boo boo")!==-1;
    if(hasText){
       setTimeout(function(){
           window.location = "http://www.example.com";
       },5000);
    }