油猴脚本: 快速复制文字到剪切板

栏目: JavaScript · 发布时间: 7年前

内容简介:由于我太懒了, 不想每次在浏览器里都要鼠标拖很长一串,然后在实现起来很简单, 选中时通过原因就是我这个人有强迫症, 如果不用

原因

由于我太懒了, 不想每次在浏览器里都要鼠标拖很长一串,然后在 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地址

只需要双击想要复制的文字或者三连击选中一长串数字就可以复制到剪切板了


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

PERL學習手札.

PERL學習手札.

簡信昌 / 上奇科技 / 20040816 / NT$ 390

1. 關於Perl 當你翻開這本書的時候,你也就進入了一個奇幻的世界。Perl確實是一種非常吸引人的程式語言,而之所以這麼引人入勝的原因不單單在於他的功能,也在於他寫作的方式,或說成為一種程式寫作的藝術。即使你只是每天埋首於程式寫作的程式設計師,也不再讓生活過份單調,至少你可以嘗試在程式碼中多一些變化。而且許多Perl的程式設計師已經這麼作了,這也是Perl的理念-「There is mor......一起来看看 《PERL學習手札.》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

URL 编码/解码
URL 编码/解码

URL 编码/解码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试