Zhihu Link Fixer

Adds a button beside Zhihu answer links to open them in FxZhihu

  1. // ==UserScript==
  2. // @name Zhihu Link Fixer
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.1
  5. // @author Frost Ming
  6. // @license MIT
  7. // @description Adds a button beside Zhihu answer links to open them in FxZhihu
  8. // @match https://www.zhihu.com/*
  9. // @match https://zhuanlan.zhihu.com/*
  10. // @grant none
  11. // @icon https://cdn.jsdelivr.net/gh/frostming/fxzhihu_bot/zhihu.webp
  12. // ==/UserScript==
  13.  
  14. function createFxZhihuButton(link) {
  15. const button = document.createElement('a');
  16. button.textContent = '复制预览链接';
  17. button.className = 'fxzhihu-button';
  18. button.style.cssText = `
  19. margin-left: 10px;
  20. padding: 2px;
  21. background-color: #0084ff;
  22. text-align: center;
  23. color: white;
  24. min-width: 82px;
  25. border-radius: 3px;
  26. font-size: 12px;
  27. text-decoration: none;
  28. transition: all 0.3s ease;
  29. `;
  30. button.addEventListener('click', (e) => {
  31. e.preventDefault();
  32. navigator.clipboard.writeText(link.replace('.zhihu.com', '.fxzhihu.com'));
  33. button.textContent = '已复制';
  34. setTimeout(() => {
  35. button.textContent = '复制预览链接';
  36. }, 1000);
  37. });
  38. button.href = 'javascript:void(0)';
  39. return button;
  40. }
  41.  
  42. (function() {
  43. 'use strict';
  44.  
  45. function addFxZhihuButton() {
  46. const answerItems = target.querySelectorAll('.ContentItem.AnswerItem');
  47. answerItems.forEach(item => {
  48. if (item.querySelector('.fxzhihu-button')) return;
  49.  
  50. let link = item.querySelector('.ContentItem-title a');
  51. if (!link) {
  52. link = item.querySelector('.ContentItem-time a');
  53. }
  54. const actions = item.querySelector('.ContentItem-actions');
  55. actions.insertBefore(createFxZhihuButton(link.href), actions.firstChild.nextSibling);
  56. });
  57. }
  58.  
  59. if (window.location.hostname.startsWith('zhuanlan.zhihu.com')) {
  60. const actions = document.querySelector('.ContentItem-actions');
  61. actions.insertBefore(createFxZhihuButton(window.location.href), actions.firstChild.nextSibling);
  62. return;
  63. }
  64.  
  65. const target = document.querySelector('.ListShortcut');
  66. if (!target) {
  67. return;
  68. }
  69. // Run the function initially
  70. addFxZhihuButton();
  71.  
  72. // Create a MutationObserver to watch for changes in the DOM
  73. const observer = new MutationObserver(addFxZhihuButton);
  74.  
  75. // Start observing the document with the configured parameters
  76. observer.observe(target, { childList: true, subtree: true });
  77. })();