以编程方式单击防止按钮

Iva*_*van 2 javascript button

我有以下按钮:

<input type="button" disabled onClick=document.location.href="?hash=blabla" tabindex="-1" class="btn btn-transparent btn-xs cbut0" />
Run Code Online (Sandbox Code Playgroud)

现在按钮被禁用并使用另一个脚本在鼠标悬停事件上重新启用它,但似乎用户仍然可以通过加载一个简单的外部JavaScript来以编程方式单击该按钮,例如:

window.onload = setTimeout(function(){
$('input.btn.btn-transparent').click();
}, 10000);
Run Code Online (Sandbox Code Playgroud)

有没有办法防止这种行为,以某种方式确保鼠标单击按钮而不是某些脚本?

我发现在" 禁用"按钮上的某些线索仍然使用".click()"触发,但在我的情况下未能实现它.

任何指针将不胜感激.谢谢.

Gan*_*nnu 5

你可以利用isTrusted财产event.看看MDN.

Event接口的isTrusted只读属性是一个布尔值,当事件由用户操作生成时为true,当事件由脚本创建或修改或通过dispatchEvent调度时为false.

演示

function changeHash(event) {
  if (event.isTrusted) {
    alert("Trusted");
  } else {
    alert("Programmatically triggered");
  }
}

function triggerClick() {
  document.getElementById('btn').click();
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

下面是检查事件是否为可信事件的示例代码.

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");
    }
Run Code Online (Sandbox Code Playgroud)

因此,使用此代码,您可以更改下面的代码以使其正常工作.

HTML

<input type="button" disabled onClick = "changeHash()" tabindex="-1" class="btn btn-transparent btn-xs cbut0" />
Run Code Online (Sandbox Code Playgroud)

JS

changeHash(event) {
    if (event.isTrusted) {
        document.location.href = "?hash=blabla"
    } else {
        event.preventDefault();
    }
}
Run Code Online (Sandbox Code Playgroud)

解决方法event.isTrusted是检查eventXeventY属性,如下所示

changeHash(event) {
    if (event.screenX  && event.screenY && event.screenX != 0 && event.screenY != 0){) {
        document.location.href = "?hash=blabla"
    } else {
        event.preventDefault();
    }
}
Run Code Online (Sandbox Code Playgroud)