Saturday, June 23, 2012

Links with Hash Not Working on Offline Mobile Browsers

Problem: On mobile browser when opening a local file, I get a white page each time I click a link with a hash (#) on it's href attribute.

Solution: Using jQuery, I applied the following javascript code to cleanup the link's href attribute by removing the href substring starting from the hash (#) sign:
$(document).ready(function() {
Link.cleanupForMobile();
});

var Device = {
    isAndroid: function() {
        return navigator.userAgent.match(/Android/i) ? true : false;
    },
    isBlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i) ? true : false;
    },
    isIos: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i) ? true : false;
    },
    isWindows: function() {
        return navigator.userAgent.match(/IEMobile/i) ? true : false;
    },
    isMobile: function() {
        return (Device.isAndroid() || Device.isBlackBerry() || Device.isIos() || Device.isWindows());
    }
};

var Link = {
cleanupForMobile: function() {
if (Device.isMobile()) {
Link._performCleanup();
}
},
_performCleanup : function() {
$("div#contentcolumn a").each(function(i, item) {
var $item = $(item);
var href= $item.attr("href");
window.console.log(href);
var hashIndex = href.indexOf("#");
if (hashIndex > -1) {
var hash = href.substr(hashIndex);
if ($(hash).length < 1) {
$item.attr("href", href.substr(0, hashIndex));
}
}
});
}
}
Note: The code above does not cover all mobile devices - only the popular ones.

No comments:

Post a Comment