Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.