Skip to content

Instantly share code, notes, and snippets.

@mqliutie
Last active April 29, 2019 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mqliutie/a0465db782c4ae34bbbc0e223442655c to your computer and use it in GitHub Desktop.
Save mqliutie/a0465db782c4ae34bbbc0e223442655c to your computer and use it in GitHub Desktop.
copy double click or triple click selected text to clipboard
// ==UserScript==
// @name copy-text-to-clipboard
// @version 0.6
// @description copy the selected text by double click or triple click to clipboard
// @author mqliutie
// @include *
// @grant unsafeWindow
// ==/UserScript==
// example online http://www.mqliutie.com/copy-text-to-clipboard.html
(function () {
'use strict';
window.__copy_text_to_clipboard__ = true;
// window.__copy_text_to_clipboard__ === true;
// iframe.contentWindow.__copy_text_to_clipboard__ === undefined
function copyToClipboard(str) {
const textAreaElement = document.createElement('textarea');
const iframe = this.__copy_text_to_clipboard__ ? document.createElement('iframe') : textAreaElement;
iframe.style.display = 'none';
textAreaElement.value = str;
document.body.appendChild(iframe);
if (this.__copy_text_to_clipboard__) {
iframe.contentDocument.body.append(textAreaElement)
}
textAreaElement.select();
document.execCommand('copy');
document.body.removeChild(iframe);
}
function mouseHandle(event) {
const detail = event.detail;
const text = this.getSelection().toString();
// if the text is empty or click event neither double click nor triple click
if (!text.trim().length || (detail !== 2 && detail !== 3)) {
return;
}
copyToClipboard.call(this, text)
}
// notice the dynamic iframes are not queried
const iframes = document.querySelectorAll('iframe');
[...iframes].forEach(iframe => {
iframe.onload = function () {
const contentWindow = iframe.contentWindow;
const contentDocument = iframe.contentDocument;
// handle iframe copy
contentDocument.addEventListener('click', mouseHandle.bind(contentWindow));
}
})
document.addEventListener('click', mouseHandle.bind(window));
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment