AtCoder to Luogu Redirect Button

Add a button to redirect from AtCoder problems to Luogu

  1. // ==UserScript==
  2. // @name AtCoder to Luogu Redirect Button
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.2
  5. // @description Add a button to redirect from AtCoder problems to Luogu
  6. // @author ChatGPT (prompted by PsychoPinkQ)
  7. // @match https://atcoder.jp/contests/*/tasks/*
  8. // @grant GM_xmlhttpRequest
  9. // @connect luogu.com.cn
  10. // @license MIT
  11. // ==/UserScript==
  12.  
  13. (function() {
  14. 'use strict';
  15.  
  16. // 取得目前 AtCoder 題目 URL 的最後部分 (例如 abc328_g)
  17. const path = window.location.pathname;
  18. const match = path.match(/contests\/(.*?)\/tasks\/(.*)/);
  19. if (!match) return;
  20.  
  21. const contest = match[1];
  22. const task = match[2];
  23. const luoguURL = `https://www.luogu.com.cn/problem/AT_${task}`;
  24.  
  25. // 創建按鈕樣式
  26. const button = document.createElement("button");
  27. button.style.position = "fixed";
  28. button.style.bottom = "60px"; // 將按鈕位置向上調整
  29. button.style.left = "20px";
  30. button.style.padding = "5px 10px"; // 調整按鈕大小
  31. button.style.backgroundColor = "rgba(173, 216, 230, 0.7)"; // 淺藍色
  32. button.style.color = "black";
  33. button.style.border = "none";
  34. button.style.borderRadius = "5px";
  35. button.style.fontSize = "12px"; // 縮小字體
  36. button.style.cursor = "pointer";
  37. button.style.zIndex = "1000";
  38. button.textContent = "查看对应 Luogu 题目";
  39.  
  40. // 檢查 Luogu 題目是否存在
  41. GM_xmlhttpRequest({
  42. method: "GET",
  43. url: luoguURL,
  44. onload: function(response) {
  45. // 判斷頁面標題是否包含「錯誤」
  46. const parser = new DOMParser();
  47. const doc = parser.parseFromString(response.responseText, "text/html");
  48. const title = doc.querySelector("title").innerText;
  49.  
  50. if (title.includes("错")) {
  51. // 題目不存在,將按鈕變為淺紅色
  52. button.style.backgroundColor = "rgba(240, 128, 128, 0.7)"; // 淺紅色
  53. button.textContent = "Luogu 似乎尚未有此题目";
  54. button.disabled = true;
  55. } else {
  56. // 題目存在,設置點擊事件
  57. button.onclick = function() {
  58. window.open(luoguURL, "_blank");
  59. };
  60. }
  61. },
  62. onerror: function() {
  63. button.style.backgroundColor = "rgba(240, 128, 128, 0.7)"; // 請求錯誤也設置為淺紅色
  64. button.textContent = "发生异常";
  65. button.disabled = true;
  66. }
  67. });
  68.  
  69. // 將按鈕加入頁面
  70. document.body.appendChild(button);
  71. })();