Wait For Elements

given a selector waits for elements to be inserted into the DOM and executes a callback for each match

当前为 2016-05-01 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/5679/122956/Wait%20For%20Elements.js

  1. /**
  2. * @param sel - the selector you want to wait for
  3. * @param action - the callback that will be executed when element/s matching the given selector are found, it is passed the array of found elements
  4. * @param stopLooking - if true the function will stop looking for more elements after the first match
  5. */
  6. function waitForElems(sel, action, stopLooking) {
  7. var id = 'fke' + Math.floor(Math.random() * 12345);
  8. var type = window.MutationObserver ? 'M' : 'S';
  9. function findElem(sel) {
  10. console.log('called find elem');
  11. var found = [].filter.call(document.querySelectorAll(sel), function(elem) {
  12. return elem.dataset[id] !== 'y';
  13. });
  14. if(found.length > 0) {
  15. if(stopLooking) {
  16. type === 'M' ? tick.disconnect() : clearInterval(tick);
  17. }
  18. found.forEach(function(elem) {
  19. elem.dataset[id] = 'y';
  20. action(elem);
  21. });
  22. }
  23. }
  24. if(type === 'M') {
  25. var tick = new MutationObserver(findElem.bind(null, sel));
  26. tick.observe(document.body, { subtree: true, childList: true });
  27. } else {
  28. var tick = setInterval(findElem.bind(null, sel), 300);
  29. }
  30. findElem(sel);
  31. return tick;
  32. }
  33. /**
  34. * @param regex - should match the site you're waiting for
  35. * @param action - the callback that will be executed when a matching url is visited
  36. * @param stopLooking - if true the function will stop waiting for another url match after the first match
  37. */
  38. function waitForUrl(regex, action, stopLooking) {
  39. function checkUrl(urlTest) {
  40. var url = window.location.href;
  41. if(url !== lastUrl && urlTest(url)) {
  42. if(stopLooking) {
  43. clearInterval(tick);
  44. }
  45. lastUrl = url;
  46. action();
  47. }
  48. lastUrl = url;
  49. }
  50. var urlTest = (typeof regex === 'function' ? regex : regex.test.bind(regex)),
  51. tick = setInterval(checkUrl.bind(null, urlTest), 300),
  52. lastUrl;
  53. checkUrl(urlTest);
  54. return tick;
  55. }