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

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

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

原因

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

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


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

查看所有标签

猜你喜欢:

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

Pro Django

Pro Django

Marty Alchin / Apress / 2008-11-24 / USD 49.99

Django is the leading Python web application development framework. Learn how to leverage the Django web framework to its full potential in this advanced tutorial and reference. Endorsed by Django, Pr......一起来看看 《Pro Django》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具