keen/keen-js

trackExternalLink does not respect event.preventDefault()

Closed this issue · 2 comments

We're running into an edge case where we have <a href="#">foo</a> and a javascript click event handler on that element. We call event.preventDefault() on the event and generate a new URL to route the browser to, but we want to track clicks of the element with keen. Problem is trackExternalLink ignores our preventDefault and goes ahead and routes the browser to the href, #, overriding our own control of the browser location. Only way to prevent that currently is to set event.metaKey = true before calling trackExternalLink.

trackExternalLink should check isDefaultPrevented on the event in addition to (or instead of) the metaKey check.

Code in question: https://github.com/keen/keen-js/blob/master/src/core/lib/trackExternalLink.js#L24-40

Thank you very much

Here is sample code to reproduce the problem...

<html>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script>
    !function(a,b){a("Keen","https://d26b395fwzu5fz.cloudfront.net/3.4.0/keen-tracker.min.js",b)}(function(a,b,c){var d,e,f;c["_"+a]={},c[a]=function(b){c["_"+a].clients=c["_"+a].clients||{},c["_"+a].clients[b.projectId]=this,this._config=b},c[a].ready=function(b){c["_"+a].ready=c["_"+a].ready||[],c["_"+a].ready.push(b)},d=["addEvent","setGlobalProperties","trackExternalLink","on"];for(var g=0;g<d.length;g++){var h=d[g],i=function(a){return function(){return this["_"+a]=this["_"+a]||[],this["_"+a].push(arguments),this}};c[a].prototype[h]=i(h)}e=document.createElement("script"),e.async=!0,e.src=b,f=document.getElementsByTagName("script")[0],f.parentNode.insertBefore(e,f)},this);
    var keen = new Keen({
        projectId: "YOUR PROJECT ID",
        writeKey: "YOUR WRITE KEY"
    });
    var keenCollection = 'keenbug';

</script>
<body>
<a href="#bad" id="clicker">Click me</a>
<br>
<br>
Clicking that link should go to #good by javascript, but keen overrides that and routes to #bad.
<script>
    $('#clicker').click(function (e) {
        e.preventDefault();
//        e.metaKey = true; // Uncomment to workaround keen bug
        keen.trackExternalLink(e, keenCollection, {tracked: true});
        window.location.href = '#good';
    });

</script>
</body>
</html>

Looks like we should use addEvent instead of trackExternalLink for this case.