对于禁止网页复制粘贴,也许你并不陌生。一些网页是直接禁止复制粘贴;一些网页,则是要求登陆后才可复制粘贴;还有一些网站,复制粘贴时会带上网站的相关来源标识信息。
| const html = document.querySelector('html'); |
| html.oncopy = () => { |
| alert('你复想制我呀'); |
| return false; |
| }; |
| html.onpaste = () => false; |
| const html = document.querySelector('html'); |
| html.oncopy = (e) => { |
| console.log(e); |
| |
| |
| }; |
| html.onpaste = (e) => { |
| console.log(e); |
| }; |
| |
| document.addEventListener('copy', () => { |
| const clipboardData = |
| event.clipboardData || event.originalEvent?.clipboardData; |
| clipboardData?.setData('text/plain', '不管复制什么,都是我!'); |
| event.preventDefault(); |
| }); |
| |
| document.addEventListener('paste', () => { |
| const clipboardData = |
| event.clipboardData || event.originalEvent?.clipboardData; |
| const text = clipboardData?.getData('text'); |
| console.log(text); |
| event.preventDefault(); |
| }); |
有什么用
- 对于注册输入密码等需要输入两次相同内容的场景,应该是需要禁止粘贴的,这时候就可以禁止对应输入框的复制粘贴动作。
- 登陆才能复制。很多网站上的页面内容是不允许复制的,这样可以防止用户或者程序恶意的去抓取页面数据