1
0

chadify.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. function handleChadClick(e, magnet) {
  2. e.preventDefault(true);
  3. const a = e.target;
  4. if (a.processing) return;
  5. a.processing = true;
  6. a.style.borderBottom = 'dotted yellow';
  7. a.title = 'Processing';
  8. browser.runtime.sendMessage({magnet}).then((response) => {
  9. a.style.borderBottom = 'dotted green';
  10. a.title = 'Added';
  11. }, (error) => {
  12. console.log(`Error: ${error}`);
  13. a.style.borderBottom = 'dotted red';
  14. a.title = `${error}`;
  15. a.processing = false;
  16. });
  17. }
  18. async function processMagnets(el) {
  19. const opts = await browser.storage.local.get("enabled");
  20. if (!opts.enabled) return;
  21. const magnets = el.querySelectorAll("a[href^='magnet:?']")
  22. for (let magnet of magnets) {
  23. if (magnet.getAttribute('data-chadded')) continue;
  24. const img = document.createElement('img');
  25. img.src = browser.runtime.getURL("logo256.png");
  26. img.style = `width: auto; height: 1.2em; vertical-align: text-bottom; padding-right: 0.3em;`;
  27. const a = document.createElement('a');
  28. a.style = 'text-decoration: none;';
  29. a.appendChild(img);
  30. a.insertAdjacentText('beforeend', 'Add to Chad Music');
  31. a.addEventListener("click", (e) => handleChadClick(e, magnet.href));
  32. magnet.insertAdjacentElement('afterend', a);
  33. magnet.setAttribute('data-chadded', 1);
  34. }
  35. }
  36. // Process page
  37. processMagnets(document.body);
  38. // Now monitor the DOM for additions and substitute emoji into new nodes.
  39. // @see https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver.
  40. const observer = new MutationObserver((mutations) => {
  41. mutations.forEach((mutation) => {
  42. if (mutation.addedNodes) mutation.addedNodes.forEach(processMagnets);
  43. });
  44. });
  45. observer.observe(document.body, {
  46. childList: true,
  47. subtree: true
  48. });