install-hook-userstylesworld.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /* global API */// msg.js
  2. 'use strict';
  3. (() => {
  4. const ORIGIN = 'https://userstyles.world';
  5. const HANDLERS = Object.assign(Object.create(null), {
  6. async 'usw-ready'() {
  7. send({type: 'usw-remove-stylus-button'});
  8. if (location.pathname === '/api/oauth/style/new') {
  9. const styleId = Number(new URLSearchParams(location.search).get('vendor_data'));
  10. const data = await API.data.pop('usw' + styleId);
  11. send({type: 'usw-fill-new-style', data});
  12. }
  13. },
  14. async 'usw-style-info-request'(data) {
  15. switch (data.requestType) {
  16. case 'installed': {
  17. const updateUrl = `${ORIGIN}/api/style/${data.styleID}.user.css`;
  18. const style = await API.styles.find({updateUrl});
  19. send({
  20. type: 'usw-style-info-response',
  21. data: {installed: Boolean(style), requestType: 'installed'},
  22. });
  23. break;
  24. }
  25. }
  26. },
  27. });
  28. window.addEventListener('message', ({data, source, origin}) => {
  29. // Some browsers don't reveal `source` to extensions e.g. Firefox
  30. if (data && (source ? source === window : origin === ORIGIN)) {
  31. const fn = HANDLERS[data.type];
  32. if (fn) fn(data);
  33. }
  34. });
  35. function send(msg) {
  36. window.postMessage(msg, ORIGIN);
  37. }
  38. })();