有些頁面不希望使用者直接複製文字或叫出右鍵選單。以下整理兩種常見寫法,並附上防止選取文字的做法。使用前提醒一句:這類限制只能提高一點點門檻,無法真正保護內容,也會影響正常使用者的操作體驗(例如螢光筆閱讀器、輔助工具),請審慎評估是否真的需要。
var message = "";
///////////////////////////////////
function clickIE() {
if (document.all) { (message); return false; }
}
function clickNS(e) {
if (document.layers || (document.getElementById && !document.all)) {
if (e.which == 2 || e.which == 3) { (message); return false; }
}
}
if (document.layers) {
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown = clickNS;
} else {
document.onmouseup = clickNS;
document.oncontextmenu = clickIE;
}
document.oncontextmenu = new Function("return false")
// 右鍵開始
if (window.Event)
document.captureEvents(Event.MOUSEUP);
function nocontextmenu() {
event.cancelBubble = true;
event.returnValue = false;
return false;
}
function norightclick(e) {
if (window.Event) {
if (e.which == 2 || e.which == 3)
return false;
} else if (event.button == 2 || event.button == 3) {
event.cancelBubble = true;
event.returnValue = false;
return false;
}
}
document.oncontextmenu = nocontextmenu; // for IE5+
document.onmousedown = norightclick; // for all others
思路是:表單元素(input、textarea、select)仍要允許選取,其餘區域則攔下選取行為。
// 禁止選擇文本
var omitformtags = ["input", "textarea", "select"];
omitformtags = omitformtags.join("|");
function disableselect(e) {
if (omitformtags.indexOf(e.target.tagName.toLowerCase()) == -1)
return false;
}
function reEnable() {
return true;
}
if (typeof document.onselectstart != "undefined")
document.onselectstart = new Function("return false");
else {
document.onmousedown = disableselect;
document.onmouseup = reEnable;
}
上面這批程式碼大量依賴 document.all、document.layers、document.captureEvents 等早已退場的 API,在今日瀏覽器上多半不會走到那些分支。若要維護舊專案,建議簡化為標準事件模型:
document.addEventListener('contextmenu', function (e) {
e.preventDefault();
});
document.addEventListener('selectstart', function (e) {
var tag = (e.target.tagName || '').toLowerCase();
if (['input', 'textarea'].indexOf(tag) === -1) {
e.preventDefault();
}
});
至于「防止複製」,如果目的只是避免內容被隨手搬走,更實際的做法是搭配 CSS 的 user-select: none,程式碼更少、效能也更好。若真的在意內容被盜用,與其依賴前端限制,不如從版權聲明、浮水印與後端存取控制著手。