Slack Code Copy Button

在 Slack 的网页版代码块上添加复制按钮

  1. // ==UserScript==
  2. // @name Slack Code Copy Button
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.1
  5. // @description 在 Slack 的网页版代码块上添加复制按钮
  6. // @author sbill
  7. // @match https://*.slack.com/*
  8. // @grant none
  9. // @license MIT
  10. // ==/UserScript==
  11.  
  12. (function () {
  13. 'use strict'
  14. // 创建一个观察器,监听 DOM 变化
  15. const observer = new MutationObserver(mutations => {
  16. // 当 <pre> 元素插入页面时
  17. mutations.forEach(mutation => {
  18. if (mutation.addedNodes.length > 0) {
  19. // 查找插入的 <pre> 元素
  20. const pres = mutation.target.querySelectorAll('.c-mrkdwn__pre')
  21. // 遍历每个 <pre> 并添加复制按钮
  22. pres.forEach(pre => {
  23. // 在 <pre> 上添加复制按钮
  24. if (pre.querySelector('button')) {
  25. return
  26. }
  27. const copyButton = document.createElement('button')
  28. copyButton.innerText = '复制'
  29. copyButton.className = 'c-button c-button--primary c-button--small'
  30. copyButton.style.position = 'absolute'
  31. copyButton.style.right = 0
  32. copyButton.style.top = 0
  33. pre.style.position = 'relative'
  34. pre.appendChild(copyButton)
  35.  
  36. // 点击复制按钮,将 <pre> 内容复制到剪贴板
  37. copyButton.addEventListener('click', () => {
  38. const button = pre.querySelector('button')
  39. pre.removeChild(button)
  40. const code = pre.innerText
  41. // 将修复后的文本复制到剪贴板
  42. navigator.clipboard.writeText(code)
  43. // 显示成功提示
  44. const prompt = document.createElement('div')
  45. prompt.innerText = '复制成功!'
  46. prompt.style.position = 'fixed'
  47. prompt.style.top = '50px'
  48. prompt.style.right = '50%'
  49. prompt.style.transform = 'translateX(50%)'
  50. prompt.style.padding = '10px 20px'
  51. prompt.style.background = 'grey'
  52. prompt.style.borderRadius = '4px'
  53. prompt.style.zIndex = 222
  54. prompt.style.color = 'lightpink'
  55. document.body.appendChild(prompt)
  56.  
  57. // 2 秒后自动移除提示
  58. setTimeout(() => {
  59. document.body.removeChild(prompt)
  60. }, 2000)
  61. })
  62. })
  63. }
  64. })
  65. })
  66.  
  67. // 以根元素为监听目标,监听子节点变动
  68. observer.observe(document.body, {
  69. childList: true,
  70. subtree: true
  71. })
  72. })()

QingJ © 2025

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