我想将 Google+ 徽章添加到页面,但是来自 https://developers.google.com/+/web/badge/ 的代码在某些浏览器中不起作用,特别是在没有第三方 cookie 支持的情况下。我想添加那个徽章,但作为 <img>
标签(如 Stack Exchange 徽章)。这可能吗?
最佳答案
为了在不使用 JavaScript 的情况下向我的网站添加 Google+ 徽章(因为我的 JavaScript 代码有问题,而且我不喜欢它依赖第三方 cookie 的方式,我编写了一个快速的 PHP 脚本,它将获取徽章的代码,将其呈现为图像,并将其输出到浏览器。
首先,我创建了一个非常简单的 HTML 页面,其中仅包含我的 Google+ 徽章代码 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>
然后我创建了以下 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);
这段代码依赖于the WebKit HTML to image tool wkhtmltoimage
正在安装在服务器上 /usr/local/bin/wkhtmltoimage
.它将 Google+ 徽章的 HTML 呈现为 PNG 图像,并以 4 小时的缓存时间将其发送到浏览器。
我个人有mod_cache
在 Apache 中启用,因此 Apache 缓存它并且服务器只需要每 4 小时运行一次这个脚本,但其他人可能应该保存生成的 PNG 文件并在它过时时重新生成。
要使用它,只需在您的页面中添加 <img>
标记指向 PHP 脚本... as seen on my site .
关于javascript - 如何将 Google+ 徽章添加为图片而不是 JavaScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21392938/