content.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. (function () {
  2. console.log("HELLO FROM PLAYLIST!", Math.floor(Math.random() * 999));
  3. function msgPlayEvt(type, target) {
  4. const payload = {
  5. type,
  6. url: window.location.href,
  7. timestamp: target.currentTime,
  8. duration: target.duration,
  9. title: document.title.replace(/ - YouTube$/, ""),
  10. };
  11. return browser.runtime.sendMessage(payload);
  12. }
  13. const vid = document.querySelector("video");
  14. if (vid) {
  15. vid.addEventListener("play", function (evt) {
  16. msgPlayEvt("play", evt.target);
  17. });
  18. vid.addEventListener("playing", function (evt) {
  19. msgPlayEvt("playing", evt.target);
  20. });
  21. vid.addEventListener("pause", function (evt) {
  22. msgPlayEvt("pause", evt.target);
  23. });
  24. vid.addEventListener("ended", function (evt) {
  25. msgPlayEvt("ended", evt.target);
  26. });
  27. }
  28. function playIt(tryAgain) {
  29. const video = document.querySelector("video");
  30. const smallPlay = document.querySelector(
  31. 'button.ytp-play-button.ytp-button[data-title-no-tooltip="Play"]',
  32. );
  33. const bigPlay = document.querySelector(
  34. "button.ytp-large-play-button.ytp-button",
  35. );
  36. if (video && video.paused && smallPlay && bigPlay) {
  37. bigPlay.click();
  38. }
  39. if ((!video || (video && video.paused)) && tryAgain > 0) {
  40. setTimeout(playIt, 500, tryAgain - 1);
  41. }
  42. }
  43. // Listen for messages from the popup or background script
  44. browser.runtime.onMessage.addListener((message) => {
  45. if (message.type === "print") {
  46. console.log("MESSAGE", message);
  47. }
  48. if (message.type === "autoplay") {
  49. setTimeout(playIt, 100, 10);
  50. }
  51. });
  52. })();