MktoMunchkin :: Use Beacon w/external Munch

by sanford

HTML

<script type="text/javascript">
    document.write(unescape("%3Cscript src='//munchkin.marketo.net/munchkin-beta.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<a id="quickClick" href="/favicon.ico">Click here</a>

JavaScript

/* 
 * Add beacon capability to Munchkin object
 */
Munchkin.beaconize = function () {

    var RE_MUNCHKIN_ENDPOINTS = /\.mktoresp.com\/webevents\/(clickLink|visitWebPage|associateLead)\?/i;

    if (navigator.sendBeacon) {
        console.log('enabling sendBeacon for critical requests');

        var nativeXHRopen = window.XMLHttpRequest.prototype.open;

        window.XMLHttpRequest.prototype.open = function (method, url, async) {
            if (RE_MUNCHKIN_ENDPOINTS.test(url)) {
                console.log('transforming request for url', url, ' into beacon');

                url += '&_method=GET&_reqtype=beacon';
                navigator.sendBeacon(url, '');
                this.abort();
            } else {
                console.log('ignoring request for url', url);

                nativeXHRopen.apply(this, arguments);
            }
        }
    } else {
        console.log('browser does not support sendBeacon');
    }
}

Munchkin.beaconize();
Munchkin.init('410-XOR-673');