Skip to content

Instantly share code, notes, and snippets.

@jeremybmerrill
Created October 3, 2016 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremybmerrill/47025213523c8e0ef4b9996ca3935643 to your computer and use it in GitHub Desktop.
Save jeremybmerrill/47025213523c8e0ef4b9996ca3935643 to your computer and use it in GitHub Desktop.
a demonstration of the shenanigans caused by the isTrusted attribute
<!DOCTYPE html>
<html>
<head>
<title>How To Cause Trouble With Events' isTrusted Attribute</title>
<meta charset="UTF-8">
<script
src="http://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
</head>
<body>
<style>
.panel {
width: 44%;
margin-left: 3%;
margin-right: 3%;
float: left;
}
.result {
background-color: #ccc;
width: 100%;
min-height: 50px;
}
.code {
margin-top: 20px;
font-family: monospace;
}
</style>
<h1>The shenanigans caused by isTrusted </h1>
<div id="container" style="max-width: 1024px; width: 100%;">
<div id="trusted" class="panel">
<h4>An ordinary click</h4>
<button>Click me</button>
<br />
<a href="#">Trigger a click event on that button.</a>
<br />
<h4>Responds only to trusted click events</h4>
<div class="result">
</div>
<h4>code: </h4>
<div class="code">
$('#trusted button').click(function(e){
if(e.originalEvent && e.originalEvent.isTrusted){
$('#trusted .result').append("<p>Click detected</p>")
}
})
$('#trusted a').click(function(e){
$('#trusted button').click();
})
</div>
</div>
<div id="untrusted" class="panel">
<h4>A triggered click</h4>
<button>Don't click me</button>
<br />
<a href="#">Trigger a click event on that button.</a>
<br />
<h4>Responds to all click events</h4>
<div class="result">
</div>
<h4>code: </h4>
<div class="code">
$('#untrusted button').click(function(e){
$('#untrusted .result').append("<p>Click detected "+(e.originalEvent && e.originalEvent.isTrusted ? "e.originalEvent.isTrusted == true" : "e.originalEvent.isTrusted == false") +"</p>")
})
$('#untrusted a').click(function(e){
$('#untrusted button').click();
})
</div>
</div>
</div>
<script type="text/javascript">
$(function(){
$('#trusted button').click(function(e){
if(e.originalEvent && e.originalEvent.isTrusted){
$('#trusted .result').append("<p>Click detected</p>")
}
})
$('#untrusted button').click(function(e){
$('#untrusted .result').append("<p>Click detected "+(e.originalEvent && e.originalEvent.isTrusted ? "e.originalEvent.isTrusted == true" : "e.originalEvent.isTrusted == false") +"</p>")
})
$('#trusted a').click(function(e){
$('#trusted button').click();
})
$('#untrusted a').click(function(e){
$('#untrusted button').click();
})
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment