Monday, November 17, 2014

Postback not happening on ASP:LinkButton with Adblock Plus

I recently had a problem while working on an ASP.NET website where I had a page doing a postback on an ASP LinkButton, except in FireFox with AdBlock enabled, the postback just wasn't happening. Clicking on the button resulted in nothing. When I examined the markup on the page it looked like this:

<a id="ctl00_ctl00_MainContent_Content_btnReserveTickets" class="btn" href="javascript:__doPostBack('/* postback param*/','')">Buy</a>

It looked like the Javascript initiating the postback should have been firing. I put a breakpoint i that __doPostBack function, but it didn't get hit. There were no console errors either. I racked my mind and googled around with no luck. The only potential solution I could find - to add a CausesValidation="false" attribute to the LinkButton - didn't work.

Finally I posed my question on StackOverflow and walther over there gave me a hint that led to the solution. He suggested that I look for AdBlock's blacklisted keywords that may have been attached to the name or attribute or something of the LinkButton, such as "ad" or "facebook" or so on and so forth.

In the end, I discovered that there was a function adding a click handler to the LinkButton that was sending a Google Analytics event, as follows:

$(anchorEl).click(function () { 
                        ga('send', 'event', 'outbound', 'click', anchorEl.href, {
                            'hitCallback':
                              function () {
                                  document.location = anchorEl.href;
                              }
                        });
                        return false;
                    }); 

It turns out that once this click event gets attached, and because it's Google Analytics, all javascript on the LinkButton gets stripped off!

In the end this blogpost guided me to a solution: I wrapped the click event binding above in the following if statement:

if (ga.hasOwnProperty('loaded') && ga.loaded === true) {
    // bind event
}
This means that if AdBlock is ever blocking Google Analytics from loading, the anchorEl's click event is never bound to that Google Analytics event (binding it successfully would be useless anyway, since Google Analytics isn't loaded), and AdBlock doesn't strip the Javascript from my LinkButton.

1 comment: