Two common ways to disable copying in the frontend
- Use JavaScript to cancel the copy operation.
- Use CSS user-select:none to prevent text selection.
📓 Note: Sites such as Jianshu, Juejin, and Zhihu often use one of these methods. Reading-oriented sites such as Qidian may combine them.
Implementing copy restrictions like those on Qidian
// 禁止右键菜单
document.body.oncontextmenu = e => {
console.log(e, '右键');
return false;
// e.preventDefault();
};
// 禁止文字选择。
document.body.onselectstart = e => {
console.log(e, '文字选择');
return false;
// e.preventDefault();
};
// 禁止复制
document.body.oncopy = e => {
console.log(e, 'copy');
return false;
// e.preventDefault();
}
// 禁止剪切
document.body.oncut = e => {
console.log(e, 'cut');
return false;
// e.preventDefault();
};
// 禁止粘贴
document.body.onpaste = e => {
console.log(e, 'paste');
return false;
// e.preventDefault();
};
// css 禁止文本选择 这样不会触发js
body {
user-select: none;
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
📓 Note: Calling e.preventDefault() can also disable the operation. The author suggests returning false to avoid explicitly accessing the event object and its methods. The example applies the restriction to document.body; it can also be scoped to selected DOM elements.
Some websites allow copying but append copyright and source information to the text. They use clipboardData, which offers three common operations: setData('text', value) inserts data, getData() retrieves it, and clearData('text') clears it.
According to MDN (n.d.), clipboardData supplies a DataTransfer object:
ClipboardEvent.clipboardData Read only
A DataTransfer object containing the data affected by the user-initiated cut, copy, or paste operation, along with its MIME type.
Drag-and-drop events also expose a DataTransfer object through event.dataTransfer.
The DataTransfer object is used to hold the data that is being dragged during a drag and drop operation. It may hold one or more data items, each of one or more data types. For more information about drag and drop, see HTML Drag and Drop API.
This object is available from the dataTransfer property of all drag events.
- ClipboardEvent#Instance properties. (n.d.). MDN docs. Retrieved January 28, 2024, from https://developer.mozilla.org/en-US/docs/Web/API/ClipboardEvent
- DataTransfer properties. (n.d.). MDN docs. Retrieved January 28, 2024, from https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer
How Zhihu appends attribution to copied text
There are two common JavaScript approaches to copying. One is document.execCommand('copy'), often seen in rich-text editor frameworks. Although deprecated, it is still supported by many browsers.
The other approach listens for the copy event and obtains the selection with window.getSelection. To add attribution, modify the text before placing it on the clipboard. Zhihu and many other websites use this approach.
Sites usually listen on particular elements. document.body.oncopy listens across the body, whereas document.getElementById('xx').oncopy listens on one element.
document.body.oncopy = (event) => {
// 是否登录,没登陆就禁止转载
if (!isLogin()) return alert('禁止转载');
event.preventDefault(); // 取消浏览器原本默认的copy事件
let authorizationInfo, // 授权信息
copyText = window.getSelection(0).toString(); // 获取被复制的文本内容,没有dom结构
if (copyText.length > 20) {
// 一般少量复制网站是允许的,字数长度超过20个,则加入授权信息
copyText = `${copyText}
作者:111,
连接:zhihui.com/article/123
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
`
}
// 兼容一下ie浏览器,ie中是window,其他浏览器是event
let clipboardData = event.clipboardData || window.clipboardData;
clipboardData.setData('text', copyText);
}
The selection API also includes document.getSelection(). Calling toString() on the selection gives its text, and empty() clears it. Selection ranges let you access individual portions of a selection; the prototype exposes further methods.
Reading text when page scripts interfere with copying
- The examples above rely on JavaScript and CSS. One option is to disable page JavaScript and unset user-select. In Chrome, open DevTools settings with F1 and select Disable JavaScript.
- If copying still fails, inspect the element’s user-select style and turn that rule off locally.
- Open the article on a phone and use a long press to select text. Mobile browsers may expose different interactions that the site’s scripts do not handle.
- Take a screenshot and use OCR.
- Save the HTML locally to read the text without the site’s CSS or JavaScript. This suits plain text.
- Open the browser console with F12, select the desired content, and evaluate
window.getSelection(0).toString();to see the selected plain text. This still requires being able to select it in the first place.
Follow-up
Articles by shigen and 捌玖ki also discuss watermarks and discouraging use of the console. Both examples rely on JavaScript, so I would expect disabling JavaScript to affect them.
Excerpts from the original discussion
I recently noticed that some sites do all sorts of interesting things when you open them:
- You cannot select text.
- You cannot copy and paste text.
- Right-clicking does not bring up a menu.
- You cannot open the console. …and so on.
The odd restrictions kept coming, reminding me of a library I encountered early on. My curiosity was piqued: how did they do it? After experimenting, I found the stated aim was to prevent website data leaks. It sounds impressive, but to me some implementations seem more about showing off or charging users.
The result is shown below.

The additions to what we discussed above are discouraging debugging and adding watermarks.
Discouraging debugging
let threshold = 160 // 打开控制台的宽或高阈值
window.setInterval(function() {
if (window.outerWidth - window.innerWidth > threshold ||
window.outerHeight - window.innerHeight > threshold) {
// 如果打开控制台,则刷新页面
window.location.reload()
}
}, 1000)
The idea is easy to follow. Open F12 DevTools and the page viewport may shrink. Compare its width with the screen width; if the difference exceeds the chosen threshold, treat the user as debugging. It was one of the better approaches I had found, but consider these questions:
How much bandwidth do frequent page reloads consume? What happens to backend load and request idempotency when refreshes repeatedly call the API? For those reasons I find it an extremely inelegant approach. Is there a better solution?
Adding a watermark
// 生成水印
function generateWatermark(keyword = 'shigen-demo') {
// 创建Canvas元素
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
// 设置Canvas尺寸和字体样式
canvas.width = 100;
canvas.height = 100;
context.font = '10px Arial';
context.fillStyle = 'rgba(0,0,0,0.1)';
// 绘制文字到Canvas上
context.fillText(keyword, 10, 50);
// 生成水印图像的URL
const watermarkUrl = canvas.toDataURL();
// 在页面上显示水印图像(或进行其他操作)
const divDom = document.createElement('div');
divDom.style.cssText = `
position: fixed;
z-index: 99999;
top: -10000px;
bottom: -10000px;
left: -10000px;
right: -10000px;
transform: rotate(-45deg);
pointer-events: none;
background-image: url(${watermarkUrl});
`;
document.body.appendChild(divDom);
}
You can use the code by adjusting a few parameters without having to understand every line. The first page watermarks I remember were in an old office automation system. Later I used a reading app whose pages were covered with watermarks, on mobile and in the browser. Many sites also encrypt data in JavaScript or encrypt API data. Measures and responses keep evolving together. What makes sense depends on the application and the system design.
Intercepting Ctrl+A when user-select:none does not block Select All
The keyboard combination depends on the system and the user’s settings. On my Mac the default for selecting all is Command+A. Since people may customize their shortcuts, the example handles both Ctrl+A and Command+A. JavaScript example: document.keyDown = function(event) { const {ctrlKey, metaKey, keyCode} = event; if((ctrlKey || metaKey) && keyCode === 65) { return false; } }
- shigen. (2023, November 22). 前端如何防止数据泄露[Blog post]. Retrieved from https://cloud.tencent.com/developer/article/2357388
- 捌玖ki. (2023, october 22). 如何防止网站信息泄露(复制/水印/控制台)[Blog post]. Retrieved from https://juejin.cn/post/7292416512333332534
- obkoro1. (2018, august 9). 前端er怎样操作剪切复制以及禁止复制+破解[Blog post]. Retrieved from https://juejin.cn/post/6844903653795446792
- 咸鱼前端clw. (2021, jan 25). 如何防止网站信息泄露(复制/水印/控制台) [Blog post]. Retrieved from https://segmentfault.com/a/1190000039087909