Facebook & Twitter Share Customized Text

I wanted to allow users to easily share content that they had input into a page onto Facebook and Twitter. Good news and bad news: It's pretty easy to set up the Tweet, but Facebook won't allow you to prepopulate a status message. The best you can do there is share your URL.

To kick things off, I created this example:

What is your favorite color?


As you can see, it's nothing fancy. Here's the code behind it:

<p>What is your favorite color?<br>
<input type="text" id="favcolor" class="text"></p>

<p><input type="button" class="button" value="Tweet" onclick="startshare('twitter');">  <input type="button" class="button" value="Share" onclick="startshare('facebook');"></p>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function startshare(platform) {
	var url = 'https://inkplant.com/code/facebook-twitter-share';
	if (platform == 'facebook') {
		var facebook_app_id = 1527787694104061; //replace this with your app ID
	} else if (platform == 'twitter') {
		var message = 'My favorite color is ' + $('#favcolor').val() + '. ' + url;
	} else {
		alert('Invalid social share platform.');

function sharetwitter(url,message) {
	var shareurl = 'https://twitter.com/intent/tweet?text=' + encodeURIComponent(message) + '&url= ' + encodeURIComponent(url);

function sharefacebook(url,facebook_app_id) {
	var shareurl = 'https://www.facebook.com/dialog/share?app_id=' + facebook_app_id + '&display=page&href=' + encodeURIComponent(url) + '&redirect_uri=' + encodeURIComponent(url);

function sharecore(shareurl) {
	var newpage = window.open(shareurl,'_blank');
	if (newpage) { newpage.focus(); } // new window opened successfully
	else { window.location = shareurl; } // browser blocked the new window, so redirect the current window instead

The Tweet button use's Twitter's Tweet Web Intent method to share the user's favorite color and the URL of the page.

The Share button uses Facebook's Share Dialog but, as I mentioned earlier, there's no way there of prepopulating the status message. So, while we're able to share the URL, we're not able to share the user's favorite color.

(There is a potential workaround here by setting up multiple URLs using query strings and then sharing those… page.html?color=pink, page.html?color=blue, for example. But that wasn't an exact match of what I was trying to do here, so I didn't pursue it.)

As it is, we'll use have to let the users come up with their own message for Facebook; all we can provide is the URL.

One note of caution: Be sure to update your Facebook App ID before using the code shown here.



This post was published on December 22nd, 2015 by Robert James Reese in the following categories: Facebook, JavaScript, jQuery, and Twitter Before using any of the code or other content in this post, you must read and agree to our terms of use.