Reputation: 11070
I'd like to add a Google+ badge to a page, however the code from https://developers.google.com/+/web/badge/ isn't working in certain browsers, specifically without third party cookie support. I want to add that badge but as an <img>
tag (like Stack Exchange badges). Is that possible?
Upvotes: 1
Views: 249
Reputation: 11070
In order to add a Google+ badge to my website, without using JavaScript (because I was having issues with the JavaScript code, and I didn't like the way it depended on third party cookies I hacked together a quick PHP script which would fetch the code for the badge, render it as an image, and output it to the browser.
First I created a very simple HTML page containing only the code for my Google+ badge from their generator:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Google +</title>
<style type="text/css">
html, body {
padding: 0;
margin: 0;
background-color: #eee;
width: 200px;
height: 280px;
overflow: hidden;
}
</style>
</head>
<body>
<!-- Place this tag where you want the widget to render. -->
<div class="g-person" data-width="200" data-href="//plus.google.com/117363378958465856853" data-theme="dark" data-showtagline="false" data-rel="author"></div>
<!-- Place this tag after the last widget tag. -->
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/platform.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
</body>
</html>
I then created the following PHP script:
<?php
$path = tempnam('/tmp','jgitlin-badge').'.png';
$html_file = realpath(dirname(__FILE__).'/googleplusbadge.html');
$cmd = "/usr/local/bin/wkhtmltoimage --javascript-delay 3000 --transparent --disable-smart-width --width 200 $html_file $path";
exec($cmd);
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($path)).' GMT', true, 200);
header('Cache-Control: max-age=14400, public',true);
header('Pragma: Public',true);
header('Expires: ' . gmdate('D, d M Y H:i:s', time()+14400) . ' GMT',true);
header('Content-Length: '.filesize($path),true);
header("Content-Type: image/png",true);
readfile($path);
This code depends on the WebKit HTML to image tool wkhtmltoimage
being installed on the server at /usr/local/bin/wkhtmltoimage
. It renders the HTML for the Google+ badge as a PNG image, and sends it to the browser with a 4-hour cache time.
I personally have mod_cache
enabled in Apache so Apache caches this and the server only needs to run this script once every 4 hours, but others should probably save the generated PNG file and regenerate if it's stale.
To use this, just add to your page an <img>
tag pointed at the PHP script... as seen on my site.
Upvotes: 2