LoginSignup
3

More than 5 years have passed since last update.

Qiitaのコードをクリックでコピーするアイコンを実装するJavaScriptを書いた

Posted at

QiitaのことなのでブログじゃなくてQiitaに載せときます。


// ==UserScript==
// @name         Show copy icon to copy code tags on Qiita
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       https://yuis-programming.com
// @match        https://qiita.com/*
// @grant        none
// ==/UserScript==


function copyTextToClipboard(text){var textArea=document.createElement("textarea");textArea.style.position='fixed';textArea.style.top=0;textArea.style.left=0;textArea.style.width='2em';textArea.style.height='2em';textArea.style.padding=0;textArea.style.border='none';textArea.style.outline='none';textArea.style.boxShadow='none';textArea.style.background='transparent';textArea.value=text;document.body.appendChild(textArea);textArea.focus();textArea.select();try{var successful=document.execCommand('copy');var msg=successful?'successful':'unsuccessful';console.log('Copying text command was '+msg)}catch(err){console.log('Oops, unable to copy')}document.body.removeChild(textArea)}

function addCSS(code){
  var css = document.createElement("style");
  css.type = "text/css";
  css.innerHTML = code;
  document.body.appendChild(css);
}

// CSS .addCopyToCodeTags を追加
addCSS('.addCopyToCodeTags::before{ opacity: 0.7 ; content: "\\f0c5";    font-family: FontAwesome;    font-style: normal;    font-weight: normal;    text-decoration: inherit;    padding-right: 1em; }')

// 全てのpreタグにaddCopyToCodeTagsクラスを付与
var i ;
for (i=0 ;i < document.querySelectorAll('pre').length ; i++){
    document.querySelectorAll('pre')[i].classList.add('addCopyToCodeTags')
}

// addCopyToCodeTagsクラスをクリックしたら同要素のinnerTextがコピーされる
[].forEach.call(document.querySelectorAll('.addCopyToCodeTags'),function(x){
  x.addEventListener("click", function(e){
    copyTextToClipboard(e.target.innerText) ;
  });
});

使用感

ShareX_ScreenShot_205d2009-0ba8-4cab-aa2d-eab3947a76bc.png (1226×697)

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3