index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import browser from 'webextension-polyfill';
  2. import { nanoid } from 'nanoid';
  3. import { toCamelCase } from '@/utils/helper';
  4. import executedBlock from './executed-block';
  5. import blocksHandler from './blocks-handler';
  6. (() => {
  7. if (window.isAutomaInjected) return;
  8. window.isAutomaInjected = true;
  9. browser.runtime.onMessage.addListener((data) => {
  10. return new Promise((resolve, reject) => {
  11. if (data.isBlock) {
  12. const removeExecutedBlock = executedBlock(
  13. data,
  14. data.executedBlockOnWeb
  15. );
  16. const handler = blocksHandler[toCamelCase(data.name)];
  17. if (handler) {
  18. handler(data)
  19. .then((result) => {
  20. removeExecutedBlock();
  21. resolve(result);
  22. })
  23. .catch(reject);
  24. return;
  25. }
  26. console.error(`"${data.name}" doesn't have a handler`);
  27. resolve('');
  28. return;
  29. }
  30. switch (data.type) {
  31. case 'content-script-exists':
  32. resolve(true);
  33. break;
  34. case 'give-me-the-frame-id':
  35. browser.runtime.sendMessage({
  36. type: 'this-is-the-frame-id',
  37. });
  38. resolve();
  39. break;
  40. case 'loop-elements': {
  41. const selectors = [];
  42. const attrId = nanoid(5);
  43. const elements = document.body.querySelectorAll(data.selector);
  44. elements.forEach((el, index) => {
  45. if (data.max > 0 && selectors.length - 1 > data.max) return;
  46. const attrName = 'automa-loop';
  47. const attrValue = `${attrId}--${index}`;
  48. el.setAttribute(attrName, attrValue);
  49. selectors.push(`[${attrName}="${attrValue}"]`);
  50. });
  51. resolve(selectors);
  52. break;
  53. }
  54. default:
  55. }
  56. });
  57. });
  58. })();