繁体   English   中英

如何添加Google+徽章作为图像而不是JavaScript?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM