core.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /**
  2. * 多说User-Agent插件核心脚本
  3. * 用于监听DUOSHUO及评论加载过程并执行注入
  4. *
  5. * @author Gerald <gera2ld@163.com>
  6. *
  7. * Optional requirements:
  8. * ./default.js
  9. */
  10. var _this = this;
  11. function emptyString(local) {
  12. return '';
  13. }
  14. var myIds;
  15. function callBefore(local, args) {
  16. if (!myIds) {
  17. myIds = duoshuoQuery.myIds || [];
  18. if (!myIds.slice) myIds = [myIds];
  19. myIds.reverse();
  20. }
  21. var e = args[0];
  22. if (args.length == 1) // embed.unstable.js
  23. e = e.post;
  24. local.agent = e.agent;
  25. local.webmaster = 0;
  26. var id = e.author_id;
  27. for (var i = myIds.length; i--; )
  28. if (myIds[i] == id) {
  29. local.webmaster = id;
  30. break;
  31. }
  32. }
  33. function callAfter(local, args) {
  34. var res = local.result;
  35. var i = res.indexOf('<div class="ds-comment-header">');
  36. var j = res.indexOf('</div>', i);
  37. var func = duoshuoQuery.getUAString || _this.getUAString || emptyString;
  38. local.result = res.slice(0, j) + func.call(_this, local) + res.slice(j);
  39. }
  40. function init() {
  41. var post = DUOSHUO.templates.post;
  42. DUOSHUO.templates.post = function () {
  43. var local = {};
  44. var args = arguments;
  45. callBefore.call(this, local, args);
  46. local.result = post.apply(this, args);
  47. callAfter.call(this, local, args);
  48. return local.result;
  49. }
  50. }
  51. function observeProperty(item, key, callback) {
  52. function callbackOnce() {
  53. var cb = callback;
  54. if (cb) {
  55. callback = null;
  56. cb();
  57. }
  58. }
  59. var value;
  60. if (item[key]) callbackOnce();
  61. else Object.defineProperty(item, key, {
  62. get: function () {return value;},
  63. set: function (val) {
  64. value = val;
  65. callbackOnce();
  66. },
  67. configurable: true,
  68. });
  69. }
  70. function observePropertyChain(item, keys, callback) {
  71. function observe() {
  72. observeProperty(item, key, function () {
  73. item = item[key];
  74. if(key = keys.shift()) observe();
  75. else callback();
  76. });
  77. }
  78. var key = keys.shift();
  79. observe();
  80. }
  81. observePropertyChain(window, ['DUOSHUO', 'templates', 'post'], init);