原因
由于我太懒了, 不想每次在浏览器里都要鼠标拖很长一串,然后在command+c
复制,所以我想快速复制.平时双击或三连击选文案的情况还是蛮多的,所以就决定实现一个油猴的脚本,这样就可以方便的玩耍了
实现
(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));})();
实现起来很简单, 选中时通过window.getSelection
获取到选中的文字,然后执行document.execCommand('copy')
拷贝到剪切板
copyToClipboard
中有一个判断, 那为什么要有这个判断呢?
原因就是我这个人有强迫症, 如果不用iframe
, 只是用textarea
会造成选中文字的失焦(选中文字不高亮),所以用了iframe
.
理想情况就不需要这个判断,无论什么情况都用iframe
来实现拷贝, 但是问题出现了, iframe在选中时候不会复制到剪切板
因此在iframe
下选中还得用textarea
...
因为iframe
不在当前文档中,因此iframe
选中的高亮不会因为textare.select()
而造成失焦
在线demo(要装油猴插件)
gist地址
只需要双击想要复制的文字或者三连击选中一长串数字就可以复制到剪切板了