油猴脚本: 快速复制文字到剪切板
栏目: JavaScript · 发布时间: 6年前
内容简介:由于我太懒了, 不想每次在浏览器里都要鼠标拖很长一串,然后在实现起来很简单, 选中时通过原因就是我这个人有强迫症, 如果不用
原因
由于我太懒了, 不想每次在浏览器里都要鼠标拖很长一串,然后在 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 (要装油猴插件)
只需要双击想要复制的文字或者三连击选中一长串数字就可以复制到剪切板了
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- 可变剪切分析
- iOS 图片压缩、滤镜、剪切、渲染等解析
- opencv笔记(2):图像剪切和图像移位
- CopyQ 3.12.0 发布,剪切板管理工具
- CopyQ 4.0.0 发布,剪切板管理工具
- CopyQ 4.1.0 发布,剪切板管理工具
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Learning Web App Development
Semmy Purewal / O'Reilly Media / 2014-3-3 / USD 29.99
Grasp the fundamentals of web application development by building a simple database-backed app from scratch, using HTML, JavaScript, and other open source tools. Through hands-on tutorials, this pract......一起来看看 《Learning Web App Development》 这本书的介绍吧!