You can't test it directly.
You definitely can test it directly by simulating a mouse click on a
link to another page or an anchor in the same page. The problem with
this test is it is too disruptive to the user experience.
I think that tonight I've discovered that you can test preventDefault
directly without the user knowing. The test link can have a
"javascript:" pseudo-protocol script for its href value.
---------------------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"
http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>preventDefault Test</title>
<script type="text/javascript">
var preventDefaultFailed = 20;
var link = document.createElement('a');
link.href = 'javascript: void(preventDefaultFailed = 21);';
link.addEventListener('click', function(e){
e.preventDefault();
}, false);
var e = document.createEvent("MouseEvents");
e.initMouseEvent('click', // event type
true, // can bubble
true, // cancelable
window, // abstract view
0, // detail
0, // screenX
0, // screenY
0, // clientX
0, // clientY
false, // ctrl key
false, // alt key
false, // shift key
false, // meta key
0, // button
null); // related target
link.dispatchEvent(e);
if (preventDefaultFailed == 20) {
alert('preventDefault worked');
}
else {
alert('preventDefault failed');
}
</script>
</head>
<body>
</body>
</html>
---------------------------------
This would need to be packaged differently for a library but the main
ideas might be ok.
This test doesn't work in Safari 2.0.4- because those browsers don't
have e.initMouseEvent. I haven't checked for that property above but
that could be added. So even though Safari 2.0.4 was the first Safari
version that can preventDefault, since it is not possible to insure
that preventDefault is working in that browsers, then the library's
preventDefault wrapper cannot be defined. That is a perfectly good use
of feature testing: if the feature test cannot be made then assume the
feature is not there or broken.
I've never used the javascript: protocol or the void operator before.
If I had, then I may have thought of this earlier. Perhaps my
inexperience with these features means I'm missing something still.
I'm going to have to sleep on this but I think the idea in the code
above can be used to make a good direct preventDefault feature test.
Then a lot of browser testing to make sure it is a good test, of
course.
Peter