[英]Prevent button from being clicked programmatically
我有以下按钮:
<input type="button" disabled onClick=document.location.href="?hash=blabla" tabindex="-1" class="btn btn-transparent btn-xs cbut0" />
现在该按钮被禁用并使用另一个脚本在鼠标悬停事件时重新启用它,但是似乎用户仍然可以通过加载一个简单的外部 javascript 以编程方式单击该按钮,例如:
window.onload = setTimeout(function(){
$('input.btn.btn-transparent').click();
}, 10000);
有什么办法可以防止这种行为,以某种方式确保按钮是由鼠标而不是由某些脚本点击的?
我发现禁用按钮上的一些线索仍然使用“.click()”触发,但在我的情况下未能实现。
您可以使用event
的isTrusted
属性。 看看MDN 。
Event 接口的 isTrusted 只读属性是一个布尔值,当事件由用户操作生成时为 true,当事件由脚本创建或修改或通过 dispatchEvent 调度时为 false。
function changeHash(event) { if (event.isTrusted) { alert("Trusted"); } else { alert("Programmatically triggered"); } } function triggerClick() { document.getElementById('btn').click(); }
<input type="button" id="btn" onClick="changeHash(event)" tabindex="-1" class="btn btn-transparent btn-xs cbut0" value="change"> <button onclick="triggerClick()">Trigger click</button>
下面是检查事件是否为可信事件的示例代码。
if ('isTrusted' in event) {
if (event.isTrusted) {
alert('The ' + event.type + ' event is trusted.');
} else {
alert('The ' + event.type + ' event is not trusted.');
}
} else {
alert('The isTrusted property is not supported by your browser');
}
因此,使用此代码,您可以像下面一样更改代码以使其正常工作。
<input type="button" disabled onClick = "changeHash()" tabindex="-1" class="btn btn-transparent btn-xs cbut0" />
changeHash(event) {
if (event.isTrusted) {
document.location.href = "?hash=blabla"
} else {
event.preventDefault();
}
}
event.isTrusted
解决方法是检查eventX
和eventY
属性,如下所示changeHash(event) {
if (event.screenX && event.screenY && event.screenX != 0 && event.screenY != 0) {
document.location.href = '?hash=blabla';
} else {
event.preventDefault();
}
}
尝试这个:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<title>JS Bin</title>
</head>
<body>
<input type="button" onmousedown="mouseDown()" value="click me" id="btn">
<input type="button" value="Btn2" id="btn2">
<p id="prevented"></p>
</body>
</html>
JS:
function mouseDown() {
alert("MD");
}
$(document).ready(function() {
$("#btn").click(function(evt) {
evt.preventDefault();
//prevented click at time:
$("#prevented").text(new Date());
});
$("#btn2").click(function() {
$("#btn").click();
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.