views:

1704

answers:

3

Is there an easy way to have JavaScript mimic a User clicking an anchor tag on a page? That means the Referrer Url needs to be set. Just setting the document.location.href doesn't set the Referrer Url.

<script>
  $(document).ready(function () {
    $("a").click();
});
</script>

<a href="http://example.com"&gt;Go here</a>

This doesn't work because there isn't a Click() event setup for the link.

+3  A: 

You could do:

window.location = $("a").attr("href");

If you want to keep the referrer, you could do this:

var href = $('a').attr('href');
$('<form>').attr({action: href, method: 'GET'}).appendTo($('body')).submit();

It is hackish, but works in all browsers.

Paolo Bergantino
I don't think this works in order to get the Referrer Url. I updated the question to reflect this.
Mm. It does on Firefox, just not on IE. Looking into it.
Paolo Bergantino
+1  A: 

Maybe something like this is what you're looking for?

$(document).ready(function () {
  $("a").each(function(){
    if($(this).click()){
      document.location.href = $(this).attr("href");
    }
  });
});
svinto
This doesn't work for because the Referrer Url doesn't get set. I updated the question
A: 

Okay, referer doesn't get set using document.location (as per my other answer), might work with window.navigate(url)? If that doesn't work the following might, though it's quite - ehrm - ugly:

$(function() {
  $("a").each(function(){
    if($(this).click()){
      $('<form method="get" action="' + $(this).attr("href") + '"></form>').appendTo("body").submit();
      return false;
    }
  });
});
svinto