更新日期:2021-04-08

通常我對這個功能毫不在意,只是某些用戶比較會 care,例如還要加入鎖右鍵功能。不過一山還有一山高,這些對懂語法的人來說,其實也沒那麼好用。

這是前端的東西,當然是以 javascript 語法為主,不囉唆直接給程式碼:

document.addEventListener('mouseup', function(){
    var selObj = window.getSelection();
    var theText = selObj.toString();
    theText += "\n\n原文網址:"+ document.title + "\n"+ window.location.href;
    console.log(theText);
    CopyToClipboard(theText);
}, false);

function CopyToClipboard (input) {
    var textToClipboard = input;

    if (window.clipboardData) { // IE
        window.clipboardData.setData ("Text", textToClipboard);
    } else {
        var forExecElement = CreateElementForExecCommand (textToClipboard);
		SelectContent (forExecElement);

        var supported = true;
        try {
            if (window.netscape && netscape.security) {
                netscape.security.PrivilegeManager.enablePrivilege ("UniversalXPConnect");
            }
            success = document.execCommand ("copy", false, null);
        } catch (e) {
            success = false;
        }
        document.body.removeChild (forExecElement);
    }
}

function CreateElementForExecCommand (textToClipboard) {
    var forExecElement = document.createElement ("div");
    forExecElement.style.position = "absolute";
    forExecElement.style.left = "-10000px";
    forExecElement.style.top = "-10000px";
    forExecElement.textContent = textToClipboard;
    document.body.appendChild (forExecElement);
    forExecElement.contentEditable = true;
    return forExecElement;
}

function SelectContent (element) {
    var rangeToSelect = document.createRange ();
    rangeToSelect.selectNodeContents (element);

    // select the contents
    var selection = window.getSelection ();
    selection.removeAllRanges ();
    selection.addRange (rangeToSelect);
}

同場加映,「禁止複製+鎖右鍵+禁止全選」語法:

function iEsc(){ return false; }
function iRec(){ return true; }

function DisableKeys() {
    if(event.ctrlKey || event.shiftKey || event.altKey) {
        window.event.returnValue=false;
        iEsc();
    }
}

document.ondragstart=iEsc;
document.onkeydown=DisableKeys;
document.oncontextmenu=iEsc;

if (typeof document.onselectstart !="undefined"){
    document.onselectstart=iEsc;
}else{
    document.onmousedown=iEsc;
    document.onmouseup=iRec;
}

function DisableRightClick(qsyzDOTnet){
if (window.Event){
    if (qsyzDOTnet.which == 2 || qsyzDOTnet.which == 3) {
      iEsc();
    }else{
        if (event.button == 2 || event.button == 3){
            event.cancelBubble = true
            event.returnValue = false;
            iEsc();
      }
   }
}