views:

569

answers:

2

I have a simple greasemonkeyscript that makes some simple dom manipulation. The greasemonkey script is loaded after the DOM is loaded, that's fine so fare and it does work for the initial Page. But on this site (it's twitter ;-) ) parts of the page get loaded after a click by xmlhttprequest and this part did not get manipulated by my greasemonkeyscript.

Is there a simple possibility to run the script again after the xmlhttprequest is loaded or after the DOM is changed by the request?

+1  A: 

A powerful technique when using Greasemonkey is to 'hijack' existing JavaScript functions. If the page you are altering has a function called 'processAjaxResponse' which is called when to process the xmlhttprequest response, the you can do the following in your Greasemonkey script. (Forgive me for not getting the syntax and parameters correct - I am an occasional user).

var originalProcessAjaxResponse;

function myNewProcessAjaxResponse{
  /* Manipulate DOM if you need to and then ... */
  originalProcessAjaxResponse();
}

function hijack {
  var originalProcessAjaxResponse = processAjaxResponse;
  processAjaxResponse = myNewProcessAjaxResponse();
}

This allows you to inject your own functionality when the ajax response event occurs.

Regards

Howard May
A: 

Thanks Howard. It was the way in the right direction.

It's quite hard to find the right entry point to hijack a function on a minifyied script. But I found that there is a huck in the twitter script. It does call window.onPageChange after the Ajax request. (I wonder if this is a common best practice in javascript and if other do this as well?) I did found some code on http://userscripts.org/scripts/review/47998 wich does use this posibility to attach events.

     if (typeof unsafeWindow.onPageChange === 'function') {
  var _onPageChange = unsafeWindow.onPageChange;
  unsafeWindow.onPageChange = function(){
   _onPageChange();
   filter();
  };
 } else {
  unsafeWindow.onPageChange = filter;
 }