jQuery: come implementare un pulsante di share su Google Plus

jQuery: come implementare un pulsante di share su Google Plus

Google Plus ha un modo radicalmente diverso rispetto ad altri social network di reperire i dati sulle condivisioni di una data pagina. Nonostante questa difficoltà, possiamo tuttavia utilizzare jQuery ed un proxy PHP per creare un pulsante di condivisione personalizzato.

Il codice PHP

Con PHP dobbiamo effettuare una richiesta POST a Google Plus utilizzando il formato JSON sia per la richiesta che per l'output restituito. Il parametro che cambierà di volta in voltà sarà l'URL della pagina di cui vogliamo conoscere il numero di condivisioni.


<?php
header( 'Content-Type: application/json' );
$url = $_GET['url'];
$data = '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"'.$url .'","source":"widget","userId":"@viewer","groupID":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]';

$ch = curl_init( 'https://clients6.google.com/rpc' );                                                                      
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, "POST" );                                                                     
curl_setopt( $ch, CURLOPT_POSTFIELDS, $data );                                                                  
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); 
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen( $data )
    )                                                                       
);                                                                                                                   
 
$result = curl_exec( $ch );
echo $result;
exit();
?>

Il codice HTML

Possiamo creare il seguente bottone personalizzato:


<a href="https://plus.google.com/share?url=#" class="gplus-button">
	<span class="count">0</span>
</a>

L'attributo href del nostro link contiene il segnaposto # che verrà poi sostituito dall'URL della pagina da condividere. L'elemento con classe count conterrà il numero di condivisioni per quella specifica pagina che reperiremo sfruttando il nostro proxy PHP.

Il codice jQuery

Con jQuery possiamo utilizzare il seguente codice:


"use strict";

(function( $ ) {
	$.fn.gplusShare = function( options ) {
	
		options = $.extend({
			count: ".count",
			ajaxURL: "google-plus.php",
			shareURL: location.href,
			popupWidth: "500",
			popupHeight: "400"
		}, options);
		
		var _addCommas = function( number ) {
			if ( number.length > 3 ) {
					var mod = number.length % 3;
					var output = ( mod > 0 ? ( number.substring( 0,mod ) ) : "" );
					for ( var i=0 ; i < Math.floor( number.length / 3 ); i++ ) {
						if ( ( mod == 0 ) && ( i == 0 ) ) {
							output += number.substring( mod + 3 * i, mod + 3 * i + 3 );
						} else {
							output+= ',' + number.substring( mod + 3 * i, mod + 3 * i + 3 );	
						}
					}
				return ( output );
			} else {
				return number;
			}
		};
		
		return this.each(function() {
			var $element = $( this ),
				$count = $element.find( options.count ),
				href = $element.attr( "href" );
			
			$element.attr( "href", href.replace( "#", options.shareURL ) );
			
			$.getJSON( options.ajaxURL, { url: options.shareURL }, function( data ) {
				var count = data[0].result.metadata.globalCounts.count;
				$count.text( _addCommas( count ) );
			});
			
			$element.on( "click", function( e ) {
				e.preventDefault();
				var uri = $element.attr( "href" );
				
				window.open( uri, "", "width=" + options.popupWidth + ",height=" + options.popupHeight );
			});
		
		});
	
	};

})( jQuery );

Il nostro plugin non fa altro che effettuare una richiesta AJAX al nostro script PHP per ottenere il numero di condivisioni per l'URL specificato nell'opzione shareURL (il suo valore predefinito è la pagina corrente). Il percorso al file PHP può essere personalizzato modificando l'opzione ajaxURL.

Il plugin inoltre sostituisce il segnaposto # con l'URL da condividere e apre una finestra popup per la condivisione le cui dimensioni possono essere specificate nelle opzioni popupWidth e popupHeight. L'elemento contenuto nell'opzione count è un elemento jQuery che mostrerà il numero totale di condivisioni.

Ecco come si usa il plugin:


"use strict";

$( document ).ready(function() {
	$( ".post" ).each(function() {
		var $post = $( this );
		var permalink = $post.find( ".post-title a" ).attr( "href" );
		var $shareBtn = $post.find( ".gplus-button" );
		
		$shareBtn.gplusShare({
			shareURL: permalink
		});
	});
});

In questo caso abbiamo simulato la presenza di una pagina contenente vari post, ognuno con il suo permalink di cui vogliamo mostrare il numero di condivisioni.

Torna su