agent-for-hackmd.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. /* eslint-disable no-console */
  13. console.log('[HackMD] Loading GROWI agent for HackMD...');
  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. insertStyle();
  36. window.addEventListener('message', (event) => {
  37. validateOrigin(event);
  38. const data = JSON.parse(event.data);
  39. switch (data.operation) {
  40. case 'getValue':
  41. console.log('getValue called');
  42. break;
  43. case 'setValue':
  44. console.log('setValue called');
  45. break;
  46. }
  47. });
  48. window.addEventListener('load', (event) => {
  49. console.log('loaded');
  50. });
  51. console.log('[HackMD] GROWI agent for HackMD has successfully loaded.');