You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
2.4 KiB

  1. /* globals Services, sendAsyncMessage, addMessageListener, removeMessageListener, content */
  2. (function() {
  3. 'use strict';
  4. let
  5. appName = 'ublock',
  6. contentBaseURI = 'chrome://' + appName + '/content/js/',
  7. listeners = {},
  8. _addMessageListener = function(id, fn) {
  9. _removeMessageListener(id);
  10. listeners[id] = function(msg) {
  11. fn(msg.data);
  12. };
  13. addMessageListener(id, listeners[id]);
  14. },
  15. _removeMessageListener = function(id) {
  16. if (listeners[id]) {
  17. removeMessageListener(id, listeners[id]);
  18. }
  19. delete listeners[id];
  20. };
  21. addMessageListener('µBlock:broadcast', function(msg) {
  22. for (var id in listeners) {
  23. listeners[id](msg);
  24. }
  25. });
  26. var observer = {
  27. unload: function(e) {
  28. Services.obs.removeObserver(observer, 'content-document-global-created');
  29. observer = listeners = null;
  30. },
  31. onDOMReady: function(e) {
  32. var win = e.target.defaultView;
  33. if (win.location.protocol === 'chrome:' && win.location.host === appName) {
  34. win.sendAsyncMessage = sendAsyncMessage;
  35. win.addMessageListener = _addMessageListener;
  36. win.removeMessageListener = _removeMessageListener;
  37. }
  38. },
  39. observe: function(win) {
  40. if (!win || win.top !== content) {
  41. return;
  42. }
  43. // baseURI is more reliable
  44. var location = Services.io.newURI(
  45. win.location.protocol === 'data:' ? 'data:text/plain,' : win.document.baseURI,
  46. null,
  47. null
  48. );
  49. if (!(win.document instanceof win.HTMLDocument
  50. && (/^https?$/.test(location.scheme)))) {
  51. return;
  52. }
  53. win = Components.utils.Sandbox([win], {
  54. sandboxPrototype: win,
  55. wantComponents: false,
  56. wantXHRConstructor: false
  57. });
  58. win.sendAsyncMessage = sendAsyncMessage;
  59. win.addMessageListener = _addMessageListener;
  60. win.removeMessageListener = _removeMessageListener;
  61. var lss = Services.scriptloader.loadSubScript;
  62. lss(contentBaseURI + 'vapi-client.js', win);
  63. lss(contentBaseURI + 'contentscript-start.js', win);
  64. if (win.document.readyState === 'loading') {
  65. let docReady = function(e) {
  66. this.removeEventListener(e.type, docReady, true);
  67. lss(contentBaseURI + 'contentscript-end.js', win);
  68. };
  69. win.document.addEventListener('DOMContentLoaded', docReady, true);
  70. }
  71. else {
  72. lss(contentBaseURI + 'contentscript-end.js', win);
  73. }
  74. }
  75. };
  76. Services.obs.addObserver(observer, 'content-document-global-created', false);
  77. addEventListener('unload', observer.unload, false);
  78. // for the Options page
  79. addEventListener('DOMContentLoaded', observer.onDOMReady, true);
  80. })();