sspnote java copy button

add java copy button

目前为 2024-08-14 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name sspnote java copy button
  3. // @namespace http://tampermonkey.net/
  4. // @version 2024年08月14日17:16:47
  5. // @description add java copy button
  6. // @author onionycs
  7. // @match https://www.sspnote.com/detail/*
  8. // @require http://code.jquery.com/jquery-3.x-git.min.js
  9. // @icon https://www.google.com/s2/favicons?sz=64&domain=sspnote.com
  10. // @grant none
  11. // @license MIT
  12. // ==/UserScript==
  13.  
  14. (function() {
  15. 'use strict';
  16.  
  17. // Your code here...
  18.  
  19. /* globals jQuery, $, waitForKeyElements */
  20. $(document).ready(function() {
  21. // 找到所有包含具有language-Java类的<code>标签的<pre>标签
  22. $('pre:has(code.language-Java)').each(function() {
  23. // 在每个找到的<pre>标签之前插入一个按钮
  24. $('<button>复制Java代码</button>').insertBefore(this).click(function() {
  25. // 找到与这个按钮相关联的<pre>标签内的<code>标签
  26. var $code = $(this).next('pre').find('code.language-Java');
  27.  
  28. // 获取<code>标签的文本
  29. var javaCodeText = $code.text();
  30.  
  31. // 复制到剪贴板
  32. navigator.clipboard.writeText(javaCodeText).then(function() {
  33. console.log('代码已复制到剪贴板');
  34. // 可以在这里添加一些UI反馈,比如改变按钮的文本或颜色
  35. $(this).text('已复制!');
  36. setTimeout(function() {
  37. $(this).text('复制Java代码'); // 恢复按钮文本
  38. }.bind(this), 2000); // 2秒后恢复
  39. }, function(err) {
  40. console.error('复制失败: ', err);
  41. });
  42.  
  43. // 注意:上面的$(this)在navigator.clipboard.writeText的回调中不指向按钮,
  44. // 所以我们需要使用.bind(this)或者将按钮保存在一个外部变量中
  45. // 这里我使用了一个匿名函数来捕获正确的this上下文
  46. (function(button) {
  47. navigator.clipboard.writeText(javaCodeText).then(function() {
  48. console.log('代码已复制到剪贴板');
  49. button.text('已复制!');
  50. setTimeout(function() {
  51. button.text('复制Java代码');
  52. }, 2000);
  53. }, function(err) {
  54. console.error('复制失败: ', err);
  55. });
  56. })($(this)); // 将$(this)(即按钮)作为参数传递给匿名函数
  57. });
  58. });
  59. });
  60. })();