I have that script:
// ==UserScript== // @name example // @include http://xxx* // @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js // ==/UserScript== var findElem = function(elems, text) { for (var i = 0; i < elems.length; i++) { if (elems[i].textContent == text) { return elems[i]; } else { var result = findElem(elems[i].children, text); if (result != undefined) { return result; } } } return; } switch (document.getElementById('my_id').value) { case "1": findElem(document.documentElement.children, "blabla1").click(); break; case "2": findElem(document.documentElement.children, "blabla2").click(); break; case "3": findElem(document.documentElement.children, "blabla3").click(); break; case "4": findElem(document.documentElement.children, "blabla4").click(); break; default: break; }
It works fine but it works only main page load. I want to run this when page changed via ajax. How can I do that?
Also please give examples with your answers. I’m newbie. I don’t know how to use things in your answers.
Advertisement
Answer
Since browser’s environment is event-driven you’ll have to either set up a timer, bind to some event that happens around update you looking for. Alternatively, you can wrap function that does update and call your code in post-hook. Obviously, you’ll need to wrap your userscript code in some function to reuse.
Here’s an example with timer set up with setInterval
(top of script is still the same):
setInterval(function(){ switch (document.getElementById('my_id').value) { case "1": findElem(document.documentElement.children, "blabla1").click(); break; case "2": findElem(document.documentElement.children, "blabla2").click(); break; case "3": findElem(document.documentElement.children, "blabla3").click(); break; case "4": findElem(document.documentElement.children, "blabla4").click(); break; default: break; } }, 1000) // if AJAX updates happen with some specific interval, set same number here to minimize useless work