Guest User

Untitled

a guest
Mar 22nd, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.89 KB | None | 0 0
  1. /*--- waitForKeyElements(): A utility function, for Greasemonkey scripts,
  2. that detects and handles AJAXed content. Forked for use without JQuery.
  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 (element) {
  10. element.text ("This comment changed by waitForKeyElements().");
  11. }
  12.  
  13. IMPORTANT: Without JQuery, this fork does not look into the content of
  14. iframes.
  15. */
  16. function waitForKeyElements (
  17. selectorTxt, /* Required: The selector string that
  18. specifies the desired element(s).
  19. */
  20. actionFunction, /* Required: The code to run when elements are
  21. found. It is passed a jNode to the matched
  22. element.
  23. */
  24. bWaitOnce /* Optional: If false, will continue to scan for
  25. new elements even after the first match is
  26. found.
  27. */
  28. ) {
  29. var targetNodes, btargetsFound;
  30. targetNodes = document.querySelectorAll(selectorTxt);
  31.  
  32. if (targetNodes && targetNodes.length > 0) {
  33. btargetsFound = true;
  34. /*--- Found target node(s). Go through each and act if they
  35. are new.
  36. */
  37. targetNodes.forEach(function(element) {
  38. var alreadyFound = element.dataset.found == 'alreadyFound' ? 'alreadyFound' : false;
  39.  
  40. if (!alreadyFound) {
  41. //--- Call the payload function.
  42. var cancelFound = actionFunction (element);
  43. if (cancelFound)
  44. btargetsFound = false;
  45. else
  46. element.dataset.found = 'alreadyFound';
  47. }
  48. } );
  49. }
  50. else {
  51. btargetsFound = false;
  52. }
  53.  
  54. //--- Get the timer-control variable for this selector.
  55. var controlObj = waitForKeyElements.controlObj || {};
  56. var controlKey = selectorTxt.replace (/[^\w]/g, "_");
  57. var timeControl = controlObj [controlKey];
  58.  
  59. //--- Now set or clear the timer as appropriate.
  60. if (btargetsFound && bWaitOnce && timeControl) {
  61. //--- The only condition where we need to clear the timer.
  62. clearInterval (timeControl);
  63. delete controlObj [controlKey];
  64. }
  65. else {
  66. //--- Set a timer, if needed.
  67. if ( ! timeControl) {
  68. timeControl = setInterval ( function () {
  69. waitForKeyElements ( selectorTxt,
  70. actionFunction,
  71. bWaitOnce
  72. );
  73. },
  74. 300
  75. );
  76. controlObj [controlKey] = timeControl;
  77. }
  78. }
  79. waitForKeyElements.controlObj = controlObj;
  80. }
Add Comment
Please, Sign In to add comment