0

Essentially, I have this website, the content of which changes depending on what the user inputs into the query string.

When the user enters mysite.com/?1 it loads content for 1 and /?2 for 2

My problem is that I have a Facebook like button within my page, and to make it work I have written this js code:

<script type="text/javascript">
    var sUrl = window.location;
    document.getElementById('fbcom').setAttribute('href', sUrl);
</script>

this gets the url and allows the user to like different content from what is technically one file.

My problem is that when a user likes for example /?1 on facebook, if someone where to click this link on their newsfeed and decide that they like it too, technically they will be liking the page /?1-with all the additional facebook code on the end of the url, so heading back to /?1 the like has not registered.

How can I modify the above code to ignore any facebook rubbish on the end of the url when they are directed from facebook?

Important: the ID /?1 can be anything from a 1 digit to a 4 digit number e.g /?1234 My current JS ability is very poor. Thanks

Sibeesh Venu
  • 18,755
  • 12
  • 103
  • 140
user2228313
  • 119
  • 1
  • 3
  • 11

2 Answers2

2

You can combine the properties of location you actually want to keep -- which seems to be protocol, host, and pathname:

var sLoc = window.location;
var sUrl = sLoc.protocol + '//' + sLoc.host + sLoc.pathname;

You can also just use the pathname as relative-from-root:

var sUrl = window.location.pathname;
Community
  • 1
  • 1
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
1

you can do that with regex:

var sUrl = window.location.toString().replace(/^(.*?)(\?.*)?$/, '$1');
razz
  • 9,770
  • 7
  • 50
  • 68
  • I have used .htaccess file to rewrite the url from site.com/?1 to site.com/1 how would I implement this into the same example but without the question mark? sorry I don't really understand your code – user2228313 Apr 15 '13 at 21:26
  • hmmm.. my code is based on the `?`, it remove the part of the string that follows it!. what would this url for i.e. `http://domain.com/test.php?user=user&data=data` become after applying your .htaccess rewrite rules? – razz Apr 15 '13 at 21:34
  • @user2228313 Note that JavaScript sees the URL as the browser sees it. If you're rewriting between `/?1` (query) server-side and `/1` (path) client-side, JavaScript will only know the `/1` (path). If instead the "query" variant is seen client-side, then the replace can be altered to look for an `&`, which should separate the `1` from any Facebook name/values. – Jonathan Lonowski Apr 15 '13 at 21:49