waitForKeyElements.js 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*--- waitForKeyElements(): A utility function, for Greasemonkey scripts,
  2. that detects and handles AJAXed content.
  3. Usage example:
  4. waitForKeyElements (
  5. "div.comments"
  6. , commentCallbackFunction
  7. );
  8. //--- Page-specific function to do what we want when the node is found.
  9. function commentCallbackFunction (jNode) {
  10. jNode.text ("This comment changed by waitForKeyElements().");
  11. }
  12. IMPORTANT: This function requires your script to have loaded jQuery.
  13. */
  14. function waitForKeyElements (
  15. selectorTxt, /* Required: The jQuery selector string that
  16. specifies the desired element(s).
  17. */
  18. actionFunction, /* Required: The code to run when elements are
  19. found. It is passed a jNode to the matched
  20. element.
  21. */
  22. bWaitOnce, /* Optional: If false, will continue to scan for
  23. new elements even after the first match is
  24. found.
  25. */
  26. iframeSelector /* Optional: If set, identifies the iframe to
  27. search.
  28. */
  29. ) {
  30. var targetNodes, btargetsFound;
  31. if (typeof iframeSelector == "undefined")
  32. targetNodes = $(selectorTxt);
  33. else
  34. targetNodes = $(iframeSelector).contents ()
  35. .find (selectorTxt);
  36. if (targetNodes && targetNodes.length > 0) {
  37. btargetsFound = true;
  38. /*--- Found target node(s). Go through each and act if they
  39. are new.
  40. */
  41. targetNodes.each ( function () {
  42. var jThis = $(this);
  43. var alreadyFound = jThis.data ('alreadyFound') || false;
  44. if (!alreadyFound) {
  45. //--- Call the payload function.
  46. var cancelFound = actionFunction (jThis);
  47. if (cancelFound)
  48. btargetsFound = false;
  49. else
  50. jThis.data ('alreadyFound', true);
  51. }
  52. } );
  53. }
  54. else {
  55. btargetsFound = false;
  56. }
  57. //--- Get the timer-control variable for this selector.
  58. var controlObj = waitForKeyElements.controlObj || {};
  59. var controlKey = selectorTxt.replace (/[^\w]/g, "_");
  60. var timeControl = controlObj [controlKey];
  61. //--- Now set or clear the timer as appropriate.
  62. if (btargetsFound && bWaitOnce && timeControl) {
  63. //--- The only condition where we need to clear the timer.
  64. clearInterval (timeControl);
  65. delete controlObj [controlKey]
  66. }
  67. else {
  68. //--- Set a timer, if needed.
  69. if ( ! timeControl) {
  70. timeControl = setInterval ( function () {
  71. waitForKeyElements ( selectorTxt,
  72. actionFunction,
  73. bWaitOnce,
  74. iframeSelector
  75. );
  76. },
  77. 300
  78. );
  79. controlObj [controlKey] = timeControl;
  80. }
  81. }
  82. waitForKeyElements.controlObj = controlObj;
  83. }