Facebook ignoring part of my query string in share URL

Dustin picture Dustin · Sep 30, 2013 · Viewed 14k times · Source

I have a page with a Facebook Share button. The URL I want to share has a query string on it that I build with javascript. Here is how I'm generating the URL to share..

queryString = "cup=blue&bowl=red&spoon=green"; 
//the values of this are actually generated by user input, don't think its important for this example though. So in this example its just a basic string.

siteURL = "http://example.com/?share=1&";
//the url without the query string

sharingURL = siteURL+queryString; 
//Combing the domain/host with query string.. sharingURL should = http://example.com?share=1&cup=blue&bowl=red&spoon=green


function FBshare(){
  shareURL = siteURL+queryString;
  console.log(shareURL);
  window.open(
     'https://www.facebook.com/sharer/sharer.php?u='+shareURL, 
     'facebook-share-dialog', 
     'width=626,height=436'); 
  return false;
}


$(".facebook").bind("click", function(){
   FBshare();
});

When facebook grabs the URL for some reason its leaving off everything that was created in the queryString variable. So the shared URL ends up being just http://example.com/?share=1. Any ideas why its leaving off the queryString variable? The correct URL gets put into the console.log just fine, plus its in the Facebook share.php URL as a query string (for example https://www.facebook.com/sharer/sharer.php?u=http://example.com/?share=1&cup=blue&bowl=red&spoon=green).. but the actual link on Facebook is incomplete.

Here is a jsFiddle. http://jsfiddle.net/dmcgrew/gawrv/

Answer

Jason P picture Jason P · Sep 30, 2013

The facebook URL comes out as this:

https://www.facebook.com/sharer/sharer.php?u=http://example.com?share=1&cup=blue&bowl=red&spoon=green

The first & and the parameter cup (as well as the other parameters) are interpreted as part of the facebook url.

Use encodeURIComponent(), which will encode special characters like &:

shareURL = encodeURIComponent(siteURL+queryString);