[英]How can I add a Google+ badge as an image, not as JavaScript?
我想在頁面上添加Google+徽章,但是https://developers.google.com/+/web/badge/上的代碼在某些瀏覽器中不起作用,特別是在沒有第三方Cookie支持的情況下。 我想將該徽章添加為<img>
標記(例如Stack Exchange徽章)。 那可能嗎?
為了在不使用JavaScript的情況下向我的網站添加Google+徽章(因為我在JavaScript代碼方面遇到了問題,而且我不喜歡它依賴第三方Cookie的方式,所以我一起破解了一個快速的PHP腳本,該腳本可以獲取徽章的代碼,將其渲染為圖像,然后將其輸出到瀏覽器。
首先,我創建了一個非常簡單的HTML頁面,其中僅包含來自其生成器的 Google+徽章的代碼:
<!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>
然后,我創建了以下PHP腳本:
<?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);
此代碼依賴於WebKit的HTML圖像工具 wkhtmltoimage
在服務器上安裝/usr/local/bin/wkhtmltoimage
。 它將Google+徽章的HTML呈現為PNG圖像,並在4小時的緩存時間內將其發送到瀏覽器。
我個人在Apache中啟用了mod_cache
,因此Apache對此進行了緩存,服務器僅需要每4小時運行一次此腳本,但是其他人可能應該保存生成的PNG文件,如果過時則可以重新生成。
要使用此功能,只需在您的頁面上添加一個指向PHP腳本的<img>
標記, 如在我的網站上所示 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.