AtCoder copy button adder

AtCoderの問題文中の文字列にの横にコピーボタンを置きます。

  1. // ==UserScript==
  2. // @name AtCoder copy button adder
  3. // @namespace https://github.com/H20-DHMO
  4. // @version 1.1
  5. // @description AtCoderの問題文中の文字列にの横にコピーボタンを置きます。
  6. // @author H20_dhmo
  7. // @license MIT
  8. // @match https://atcoder.jp/contests/*
  9. // @grant none
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14.  
  15. // copy button
  16. function copyButton() {
  17. window.getSelection().removeAllRanges();
  18. try {
  19. const targetId = $(this).data('target');
  20. const text = $('#' + targetId).text();
  21. navigator.clipboard.writeText(text).then(() => {
  22. $(this).tooltip('show');
  23. $(this).blur();
  24. setTimeout(() => { $(this).tooltip('hide'); }, 800);
  25. });
  26. } catch (err) {
  27. console.log(err);
  28. }
  29. window.getSelection().removeAllRanges();
  30. }
  31.  
  32.  
  33. function addCopyButton(element) {
  34. // コピー用のボタン(span要素)を作成
  35. const uuid = self.crypto.randomUUID();
  36. element.setAttribute('id', uuid);
  37.  
  38. const copyBtn = $(`<span class="btn btn-default btn-xs btn-copy ml-1" tabindex="0" data-toggle="tooltip" data-trigger="manual" title="Copied!" data-target="${uuid}">Copy</span>`);
  39. $(element).after(copyBtn);
  40. copyBtn.click(copyButton);
  41. }
  42.  
  43. // 問題内の<code>要素を取得
  44. const codes = document.querySelectorAll('#task-statement .part code');
  45. codes.forEach(function(elm) {
  46. addCopyButton(elm);
  47. });
  48.  
  49. })();