Search code examples
jqueryregexexpressionuserscriptstampermonkey

How to script jquery to reload page if regular expression match not found


I'd like to look/search a webpage body for a regular expression that matches (in this example PO123456 should). If found I'd like an alert saying it was found and the script to stop running. If a RegEx match was not found I'd like it to reload the page repeatedly until a match is found. I will then paste this script into TamperMonkey to use on a page that currently requires me to press refresh repeatedly like a lab animal.

The following does not work, yet...

// ==UserScript==
// @name         Reload Page If RegEx Match Not Found
// @namespace   
// @version      0.1
// @description  Reloads Page Until RegEx Match Found
// @author       TJ
// @match        https://system.fakepage.com/someotherpage
// @grant        none
// ==/UserScript==

$(document).ready(function()
{
    var regex = /^PO\d{6}g/;
    var PO = str.match(regex);

    if($('body:contains("' + PO + '")').length > 0)
    {
    alert("Found: " + PO);
    }
    else
    {
        location.reload();
    }
});

Please help the bird out smart the pavlovian control system by helping me figure this script out! (once tested I'd like to do away with the alert.)


Solution

  • // ==UserScript==
    // @name         Reload Page If RegEx Match Not Found
    // @namespace   
    // @version      0.1
    // @description  Reloads Page Until RegEx Match Found
    // @author       TJ
    // @match        https://system.fakepage.com/someotherpage
    // @grant        none
    // ==/UserScript==   
    $(document).ready(function() {
        var regex = /PO\d{6}/g;
        var PO = document.body.innerHTML.match(regex);
        if (PO) {
            console.log("Found:",PO);
        } else {
            location.reload();
        }
    });