Auto play in MPV

Automatically redirect to mpv player when playing online video

  1. // ==UserScript==
  2. // @name Auto play in MPV
  3. // @description Automatically redirect to mpv player when playing online video
  4. // @author lxl66566
  5. // @namespace https://github.com/lxl66566/auto-play-in-mpv
  6. // @version 0.1.2
  7. // @icon https://mpv.io/images/mpv-logo-128-0baae5aa.png
  8. // @run-at document-start
  9. // @license MIT
  10. // @grant window.close
  11. // @match *://*.bilibili.com/*
  12. // @match *://bilibili.com/*
  13. // @match *://youtube.com/*
  14. // @match *://*.youtube.com/*
  15. // ==/UserScript==
  16.  
  17. (function () {
  18. // rome-ignore lint/suspicious/noRedundantUseStrict:
  19. "use strict";
  20.  
  21. // 要拦截的URL模式
  22. const targetPatterns = [
  23. "https://www.bilibili.com/video/*",
  24. "https://live.bilibili.com/*",
  25. "https://www.bilibili.com/bangumi/play/*",
  26. "https://www.youtube.com/watch*",
  27. "https://www.youtube.com/playlist*",
  28. ];
  29.  
  30. const socket = new WebSocket("ws://localhost:5777");
  31. socket.onopen = function () {
  32. console.log("WebSocket connection established");
  33. };
  34. socket.onmessage = function (event) {
  35. console.log("Message from server: ", event.data);
  36. };
  37. socket.onclose = function () {
  38. console.log("WebSocket connection closed");
  39. };
  40. socket.onerror = function (error) {
  41. console.error("WebSocket error: ", error);
  42. };
  43.  
  44. function sendUrlToServerAndClose(url) {
  45. if (socket.readyState === WebSocket.OPEN) {
  46. socket.send(url);
  47. console.log("auto-play-in-mpv: url send to socket");
  48.  
  49. // close window if received any ack message
  50. socket.onmessage = function (event) {
  51. console.log("auto-play-in-mpv: received ack server");
  52. socket.close();
  53. window.close();
  54. };
  55. } else {
  56. console.error("WebSocket is not open");
  57. // do not close window
  58. }
  59. }
  60.  
  61. function trigger() {
  62. const url = window.location.href;
  63. console.log("auto-play-in-mpv: get url: ", url);
  64. if (targetPatterns.some((pattern) => url.match(pattern))) {
  65. console.log("auto-play-in-mpv: url match");
  66. sendUrlToServerAndClose(url);
  67. }
  68. }
  69.  
  70. window.addEventListener("DOMContentLoaded", trigger, false); // for bilibili
  71. window.addEventListener("hashchange", trigger, false); // for youtube
  72.  
  73. // const originalOpen = window.open;
  74. // window.open = function (url, ...args) {
  75. // console.log("捕获到新页面打开请求:", url);
  76. // // return originalOpen.call(window, url, ...args); // 若允许则执行
  77. // return null; // 若阻止则返回 null
  78. // };
  79. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址