agent-for-hackmd.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /**
  2. * GROWI agent for HackMD
  3. *
  4. * This file will be transpiled as a single JS
  5. * and should be load from HackMD head via 'lib/routes/hackmd.js' route
  6. *
  7. * USAGE:
  8. * <script src="${hostname of GROWI}/_hackmd/load-agent"></script>
  9. *
  10. * @author Yuki Takei <yuki@weseek.co.jp>
  11. */
  12. // import { debounce } from 'throttle-debounce';
  13. /* eslint-disable no-console */
  14. const allowedOrigin = '{{origin}}'; // will be replaced by swig
  15. const styleFilePath = '{{styleFilePath}}'; // will be replaced by swig
  16. /**
  17. * Validate origin
  18. * @param {object} event
  19. */
  20. function validateOrigin(event) {
  21. if (event.origin !== allowedOrigin) {
  22. console.error('[HackMD] Message is rejected.', 'Cause: "event.origin" and "allowedOrigin" does not match');
  23. return;
  24. }
  25. }
  26. /**
  27. * Insert link tag to load style file
  28. */
  29. function insertStyle() {
  30. const element = document.createElement('link');
  31. element.href = styleFilePath;
  32. element.rel = 'stylesheet';
  33. document.getElementsByTagName('head')[0].appendChild(element);
  34. }
  35. function postMessageOnSave() {
  36. console.log('notifyChanges');
  37. window.parent.postMessage('notifyChanges', allowedOrigin);
  38. }
  39. function addEventListenersToCodemirror() {
  40. // get CodeMirror instance
  41. const editor = window.editor;
  42. editor.on('change', (cm, change) => {
  43. postMessageOnSave();
  44. });
  45. }
  46. /**
  47. * main
  48. */
  49. (function() {
  50. // check HackMD is in iframe
  51. if (window === window.parent) {
  52. console.log('[GROWI] Loading agent for HackMD is not processed because currently not in iframe');
  53. return;
  54. }
  55. console.log('[HackMD] Loading GROWI agent for HackMD...');
  56. insertStyle();
  57. // Add event listeners
  58. window.addEventListener('message', (event) => {
  59. validateOrigin(event);
  60. const data = JSON.parse(event.data);
  61. switch (data.operation) {
  62. case 'getValue':
  63. console.log('getValue called');
  64. break;
  65. case 'setValue':
  66. console.log('setValue called');
  67. break;
  68. }
  69. });
  70. window.addEventListener('load', (event) => {
  71. console.log('loaded');
  72. addEventListenersToCodemirror();
  73. });
  74. console.log('[HackMD] GROWI agent for HackMD has successfully loaded.');
  75. }());