恢复 Tiktok 无版权音乐播放

优化性能,避免重复加载和设置

  1. // ==UserScript==
  2. // @name 恢复 Tiktok 无版权音乐播放
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.1
  5. // @description 优化性能,避免重复加载和设置
  6. // @author wzj042
  7. // @match https://www.tiktok.com/*/video/*
  8. // @grant none
  9. // @icon https://www.google.com/s2/favicons?sz=64&domain=tiktok.com
  10. // @run-at document-end
  11. // @license MIT
  12. // ==/UserScript==
  13.  
  14. (function () {
  15. function setVideoToPlay() {
  16. var musicLink = document.querySelector("h4 a");
  17. var copyright = musicLink
  18. ? musicLink.href === "https://www.tiktok.com/"
  19. : false;
  20.  
  21. if (copyright) {
  22. var video = document.querySelector("video");
  23.  
  24. if (video && video.muted && video.volume > 0) {
  25. video.muted = false;
  26. // 尝试播放视频
  27. video.play().catch((e) => {
  28. if (e.name !== "NotAllowedError") {
  29. console.error(e);
  30. }
  31. });
  32. }
  33. // 更新来源
  34. if (musicLink && !musicLink.dataset.labelSet) {
  35. var script = document.getElementById(
  36. "__UNIVERSAL_DATA_FOR_REHYDRATION__"
  37. );
  38. if (script) {
  39. var data = JSON.parse(script.textContent || script.innerText);
  40. var music =
  41. data.__DEFAULT_SCOPE__["webapp.video-detail"].itemInfo.itemStruct
  42. .music;
  43. var musicLabel = `${music.title}-${music.authorName}`;
  44. musicLink.innerText = musicLabel;
  45. musicLink.dataset.labelSet = true; // 标记已设置
  46. }
  47. }
  48. }
  49. }
  50.  
  51. setInterval(setVideoToPlay, 1000);
  52. })();