content.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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: PlaylistUtils.cleanVideoUrl(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. // YouTube is a SPA: advancing to the next video in a queue swaps in a new
  14. // <video> element without a full page load, so a listener attached to one
  15. // specific element (grabbed once at injection time) stops receiving events.
  16. // Listening on `document` in the capture phase catches every video, past or
  17. // future, while `#movie_player` scopes this to the standard watch-page
  18. // player only (excludes home/search hover-preview thumbnails, Shorts, etc).
  19. ["play", "playing", "pause", "ended"].forEach(function (type) {
  20. document.addEventListener(
  21. type,
  22. function (evt) {
  23. if (
  24. evt.target.tagName === "VIDEO" &&
  25. evt.target.closest("#movie_player")
  26. ) {
  27. msgPlayEvt(type, evt.target);
  28. }
  29. },
  30. true,
  31. );
  32. });
  33. function playIt(tryAgain) {
  34. const video = document.querySelector("video");
  35. const smallPlay = document.querySelector(
  36. 'button.ytp-play-button.ytp-button[data-title-no-tooltip="Play"]',
  37. );
  38. const bigPlay = document.querySelector(
  39. "button.ytp-large-play-button.ytp-button",
  40. );
  41. if (video && video.paused && smallPlay && bigPlay) {
  42. bigPlay.click();
  43. }
  44. if ((!video || (video && video.paused)) && tryAgain > 0) {
  45. setTimeout(playIt, 500, tryAgain - 1);
  46. }
  47. }
  48. // Listen for messages from the popup or background script
  49. browser.runtime.onMessage.addListener((message) => {
  50. if (message.type === "print") {
  51. console.log("MESSAGE", message);
  52. }
  53. if (message.type === "autoplay") {
  54. setTimeout(playIt, 100, 10);
  55. }
  56. });
  57. })();