Reputation: 738
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.
Upvotes: 2
Views: 4774
Reputation: 11
If your host is using jQuery, then you can use ajaxSuccess or ajaxComplete:
function mainCode(){
// your script logic here ...
switch (document.getElementById('my_id').value) {
// truncated to save space
}
}
$(document).ready(function(){
mainCode();
unsafeWindow.$(document).ajaxSuccess(function(e, xhr, opt) {
mainCode();
});
});
Upvotes: 1
Reputation: 22421
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
Upvotes: 3
Reputation: 51181
You could use the mutation event handler to trigger your function each time the html is altered. However, browsersupport is not the best;)
Upvotes: 0