AirCopy

A simple userscript for copying text against website blocking copy.

// ==UserScript==
// @name         AirCopy
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  A simple userscript for copying text against website blocking copy.
// @author       firetree
// @match        *://*/*
// @grant        GM_addStyle
// @grant        unsafeWindow
// @run-at       document-start
// @license      GPL3
// ==/UserScript==

(function() {
    'use strict';

    GM_addStyle(`

.aircopy--notification {
    position: fixed;
    bottom: 40px;
    left: 40px;
    background: white;
    opacity: 0.5;
}
    `)

    const makeElement = (text) => {
        let result = document.createElement("div")
        result.textContent = text
        return result
    }

    const notify = (text) => {
        let element = makeElement(text)
        document.body.appendChild(element)
        element.classList.add("aircopy--notification")
        setTimeout(() => {
            document.body.removeChild(element)
        }, 1000)
    }

    const maxlen = 10

    document.addEventListener('copy', async (e) => {
        let clipboardData = e.clipboardData
        if (!clipboardData) return
        let text = unsafeWindow.getSelection().toString()
        let repr = `"` + (text.length > maxlen ? `${text.slice(0, maxlen)}...` : text) + `"`
        console.log(`[AirCopy] On copying ${repr}`)
        if (text) {
            e.preventDefault()
            clipboardData.setData('text/plain', text)
            console.log(`[AirCopy] Written ${repr} to clipboard with ClipboardEvent.clipboardData()`)
            setTimeout(async () => {
                await unsafeWindow.navigator.clipboard.writeText(text)
                console.log(`[AirCopy] Written ${repr} to clipboard with Clipboard.writeText()`)
                notify("[AirCopy] Copied!")
            });
        }
    }, { capture: true })
})();