Hijacking Local Links Only

Like most sites, ours has links to external pages (i.e., pages hosted on other domains). We shouldn't hijack these external links, because it wouldn't make sense to inject their HTML into our Android-specific layout. As shown in Example 3-9, we can add a conditional that checks the URL for the existence of our domain name. If it's found, the link is hijacked and the content is loaded into the current page (i.e., Ajax is in effect). If not, the browser will navigate to the URL normally.

You must change jonathanstark.com to the appropriate domain or hostname for your website, or the links to pages on your website will no longer be hijacked.

Example 3-9. You can allow external pages to load normally by checking the domain name of the URL

function hijackLinks() {

$('#container a').click(function(e){ var url = e.target.href; if (url.match(/jonathanstark.com/)) {

e.preventDefault(); loadPage(url);

var title = $('h2').html() || 'Hello!'; $('hl').html(title); $('h2').remove(); $('#progress').remove();

The url.match function uses a language, regular expressions, that is often embedded within other programming languages such as JavaScript, PHP, and Perl. Although this regular expression is simple, more complex expressions can be a bit intimidating, but are well worth becoming familiar with. My favorite regex page is located at http://www.regular -expressions.infojavascriptexample.html.

0 0

Post a comment