javascript 如何检测javascript中的复制和粘贴?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10827256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to detect copy and paste in javascript?
提问by StaticVariable
i have two field one is emailid and another is password in my form. i want to detect that when user reenter the email and password than he should not able to copy the above. he have to write again manually.Just like google forms
我有两个字段,一个是 emailid,另一个是我的表单中的密码。我想检测当用户重新输入电子邮件和密码时,他应该无法复制上述内容。他必须手动重新编写。就像谷歌表格一样
回答by blasteralfred Ψ
You could disable ctrl+v
combination and right click
as well.
您也可以禁用ctrl+v
组合right click
。
for IE, you may tap into following event handlers:
对于 IE,您可以使用以下事件处理程序:
onpaste="return false;"
oncut="return false;"
oncontextmenu="return false;"
oncopy="return false;".
Here is a workaround for all browsers:
这是适用于所有浏览器的解决方法:
function noCTRL(e) {
var code = (document.all) ? event.keyCode : e.which;
var ctrl = (document.all) ? event.ctrlKey : e.modifiers & Event.CONTROL_MASK;
var msg = "Sorry, this functionality is disabled.";
if (document.all) {
if (ctrl && code == 86) {
//CTRL+V
alert(msg);
window.event.returnValue = false;
} else if (ctrl && code == 67) {
//CTRL+C (Copy)
alert(msg);
window.event.returnValue = false;
}
} else {
if (ctrl == 2) {
//CTRL key
alert(msg);
return false;
}
}
}
In HTML section, your fields would look like:
在 HTML 部分,您的字段将如下所示:
Email :<input name="email" type="text" value=""/><br/>
Password :<input name="password" type="password" value=""/><br/>
Confirm Email :<input name="email" type="text" value="" onkeydown="return noCTRL(event)"/>
Confirm Password :<input name="password" type="password" value="" onkeydown="return noCTRL(event)"/>
I don't think user can copy password fields if input type is password
如果输入类型是,我认为用户不能复制密码字段 password
Hope this helps.
希望这可以帮助。
Note:
笔记:
- Disabling JavaScript in browser will let users do whatever they want
- Always Keep this in mind: respect user's freedom.
- 在浏览器中禁用 JavaScript 会让用户为所欲为
- 始终牢记这一点:尊重用户的自由。
回答by potato
2020 update
2020年更新
There are copy
and paste
events you can use to prevent these actions, or to modify the data being copied or pasted. (see the links for browser support)
有copy
和paste
你可以用它来防止这些行为,或修改数据被复制或粘贴事件。(请参阅浏览器支持的链接)
const elem = document.getElementById('nopaste');
elem.addEventListener('paste', (event) => {
event.preventDefault();
});
<input type="text" placeholder="can paste"><br>
<input type="text" id="nopaste" placeholder="can not paste">