如果页面包含特定文本,则重新加载(使用javascript)

Joh*_*ith 2 javascript fluid-mac-app-engine greasekit

如果We are sorry but we made a boo boo出现文本

  1. 等5秒钟
  2. 重装

我想用JavaScript做到这一点.

这是一次尝试

(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();
}
Run Code Online (Sandbox Code Playgroud)

我认为,如果文本出现在特定的地方,上述内容应该适用于该文本.我想让它更通用 - 以便文本可以出现在该页面的任何位置.

另外,我想知道如何添加暂停,以便例如在重新加载之前等待5秒.

我想我会添加类似的东西:

setTimeout(
function() 
{
//location.reload();
}, 5000);
Run Code Online (Sandbox Code Playgroud)

Pat*_*ans 8

只需在body的textContent/innerText属性上执行indexOf

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);
}
Run Code Online (Sandbox Code Playgroud)

  • @JohnSmith,它只是一个例子,重新加载只做`window.location.reload()` (2认同)