为站点添加每日一句的简单方法
2020 水文第二篇,为任意站点添加英文每日一句,随机从金山词霸、有道词典、欧路词典、海词词典和扇贝英语获取内容。你可在博客首页查看效果,大佬请跳过。
引入 JS
将以下代码加入到 <head>
标签中。对于本主题,依次进入 控制台 - 外观 - 设置外观 - 主题自定义扩展
,将代码加入到 自定义 HTML 元素拓展 - 标签: head 头部 (meta 元素后)
,也可直接加入到主题对应的 header.php
中的 </head>
标签前。
<script>
// 获取每日一句并显示
document.addEventListener('DOMContentLoaded', initDescription);
function initDescription() {
// 锚点开始
if (location.href !== location.origin + '/') return;
const h1 = document.querySelector('h1.blog-title');
const h2 = document.querySelector('h2.blog-description');
// 锚点结束
const local = {
set: (key, value) => localStorage.setItem(key, JSON.stringify(value)),
get: key => {
const value = JSON.parse(localStorage.getItem(key));
if (value && new Date(value.date).toDateString() !== new Date().toDateString()) return null;
return value;
}
};
const render = (data, save) => {
h1.innerHTML = data.sentence, h2.innerHTML = data.translation;
if (save) local.set('sentence', data);
};
const data = local.get('sentence');
if (data) { render(data); return; }
fetch('//logi.im/api/sentence/').then(response => response.json()).then(json => render(json, true));
}
</script>
如果你开启了 PJAX
,可能需要单独加入回调函数。对于本主题,依次进入 控制台 - 外观 - 设置外观 - PJAX(BETA) - PJAX RELOAD
,将 initDescription();
添加进入即可。
其他主题
其他主题需要通过 F12 找到对应锚点,替换代码中那三行,不知道怎么找的,留下 博客链接
和 要加入的位置
,我看到后会将锚点代码更新到此。
[tabs]
[tab title="CREAMY"]
[button href="https://sole.wzfou.me"]演示地址[/button]
if (location.href !== location.origin + '/index.php') return;
const h1 = document.querySelector('h1.site-name');
const h2 = document.querySelector('h2.site-description');
[/tab]
[/tabs]
如果你想自行部署 API,回复后刷新页面即可获取 PHP 源码。
[hide]
<?php
/**
* Date: 2020-01-12
* Copyright: @LOGI
* Support URL: https://logi.im
*
* 海词词典
* http://m.dict.cn/daily.php
*
* 金山词霸
* http://open.iciba.com/dsapi/
* http://sentence.iciba.com/?c=dailysentence&m=getTodaySentence
* http://sentence.iciba.com/?c=dailysentence&m=getdetail&title=2019-01-07
*
* 扇贝英语
* https://web.shanbay.com/op/quotes/2019-04-09
* https://rest.shanbay.com/api/v2/quote/quotes/today/
* https://apiv3.shanbay.com/weapps/dailyquote/quote/?date=2019-06-29
*
* 有道词典
* http://dict.youdao.com/infoline/style/cardList?style=daily&client=mobile
*
* 欧路词典
* GET /api/v2/appsupport/DictMobileStartupContent HTTP/1.1
* Authorization: QYN eyJ1c2VyaWQiOiIiLCJ0b2tlbiI6IiIsInZfZGljdCI6ZmFsc2UsInVybHNpZ24iOiJVdzVJbWZaaVZaWVpTTVZhU3Y3cEg1TVhlbTQ9IiwidmYiOjAsInQiOiJBQklNVFU1T1RZME5EUTBNQT09IiwiZmwiOjAsImxjIjowfQ==
* User-Agent: /eusoft_eudic_en_android/7.5.0/cdb00fcf112cf5a6///
* EudicUserAgent: /eusoft_eudic_en_android/7.5.0/cdb00fcf112cf5a6///
* EudicTimezone: 8
* Host: api.frdic.com
*/
$SUPPORT_URL = 'https://logi.im';
$API = [
'hici' => ['url' => 'http://m.dict.cn/daily.php', 'schema' => [
'sentence' => '/<div class="daily-cc">.+<p.+>(.+)<\/p>.+<\/div>/Us',
'translation' => '/<div class="daily-cc-ch">(.+)<\/div>/Us',
'source' => '/<div class="daily-cc-auth">—(.+)<\/div>/Us',
'pictures' => '/<div class="daily-pic1"><img.+src="(.+)" \/><\/div>/Us',
]],
'shanbay' => ['url' => 'https://apiv3.shanbay.com/weapps/dailyquote/quote/'],
'ciba' => ['url' => 'http://sentence.iciba.com/?c=dailysentence&m=getTodaySentence'],
'youdao' => ['url' => 'http://dict.youdao.com/infoline/style/cardList?style=daily&client=mobile'],
'eudic' => [
'url' => 'https://api.frdic.com/api/v2/appsupport/DictMobileStartupContent',
'header' => array(
"Authorization: QYN eyJ1c2VyaWQiOiIiLCJ0b2tlbiI6IiIsInZfZGljdCI6ZmFsc2UsInVybHNpZ24iOiJVdzVJbWZaaVZaWVpTTVZhU3Y3cEg1TVhlbTQ9IiwidmYiOjAsInQiOiJBQklNVFU1T1RZME5EUTBNQT09IiwiZmwiOjAsImxjIjowfQ==",
"User-Agent: /eusoft_eudic_en_android/7.5.0/cdb00fcf112cf5a6///",
),
],
];
function getContet($api)
{
if (empty($api['header'])) {
$api['header'] = array(
'User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/9B176 MicroMessenger/4.3.2',
);
}
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $api['url'],
CURLOPT_HTTPHEADER => $api['header'],
CURLOPT_RETURNTRANSFER => true,
]);
$response = curl_exec($curl);
curl_close($curl);
if (empty($api['schema'])) {
return $response;
}
foreach ($api['schema'] as $key => $value) {
preg_match($value, $response, $match);
$result[$key] = $match[1];
}
return json_encode($result);
}
function jsonDump($data)
{
return stripslashes(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
}
function response($data)
{
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json; charset=utf-8');
exit($data);
}
$api = @$_GET['api'];
if (empty($api)) {
$index = rand(0, count($API) - 1);
$api = array_keys($API)[$index];
}
$data = json_decode(getContet($API[$api]), true);
$failure = jsonDump([
'sentence' => 'Suffering produces character, and character produces hope, and hope does not disappoint us.',
'translation' => '痛苦制造性格,性格制造希望,而希望不会让我们失望。',
'source' => '林书豪',
'pictures' => ['http://dc.dict.cn/v/06723845/e9533ec4f731769cdf3fdca0d39090b7/ddsen/1/ddsen20130801.jpg'],
'code' => 1,
'message' => '解析失败',
'date' => date('Y-m-d'),
'api' => $api,
'support_url' => $SUPPORT_URL
]);
if (empty($data)) {
response($failure);
}
try {
switch ($api) {
case 'ciba':
$result = [
'sentence' => $data['content'],
'translation' => $data['note'],
'source' => '',
'pictures' => [
$data['picture2'],
$data['picture'],
$data['picture3'],
],
];
break;
case 'youdao':
$data = $data[0];
$result = [
'sentence' => $data['title'],
'translation' => $data['summary'],
'source' => $data['source'],
'pictures' => $data['image'],
];
break;
case 'shanbay':
$result = [
'sentence' => $data['content'],
'translation' => $data['translation'],
'source' => $data['author'],
'pictures' => $data['poster_img_urls'],
];
break;
case 'eudic':
$result = [
'sentence' => $data['sentence']['line'],
'translation' => $data['sentence']['linecn'],
'source' => '',
'pictures' => [$data['sentence']['img']],
];
break;
case 'hici':
$data['pictures'] = array($data['pictures']);
$result = $data;
}
if (empty($result)) {
response($failure);
}
$result['code'] = 0;
$result['message'] = '解析成功';
$result['date'] = date('Y-m-d');
$result['api'] = $api;
$result['support_url'] = $SUPPORT_URL;
response(jsonDump($result));
} catch (Exception $e) {
response($failure);
}
[/hide]
当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »