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

缘由

因为我太懒了, 不想每次在浏览器里都要鼠标拖很长一串,而后在command+c复制,因此我想快速复制.平时双击或三连击选文案的状况仍是蛮多的,因此就决定实现一个油猴的脚本,这样就能够方便的玩耍了javascript

实现

(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')拷贝到剪切板html

copyToClipboard 中有一个判断, 那为何要有这个判断呢?

缘由就是我这我的有强迫症, 若是不用iframe, 只是用textarea会形成选中文字的失焦(选中文字不高亮),因此用了iframe.java

理想状况就不须要这个判断,不管什么状况都用iframe来实现拷贝, 可是问题出现了, iframe在选中时候不会复制到剪切板 所以在iframe下选中还得用textarea...git

由于iframe不在当前文档中,所以iframe选中的高亮不会由于textare.select()而形成失焦github

在线demo(要装油猴插件)浏览器

gist地址app

只须要双击想要复制的文字或者三连击选中一长串数字就能够复制到剪切板了.this

相关文章
相关标签/搜索