实现随机Banner

本文最后更新于:2023年8月19日 下午

起因

Hexo-theme-fluid 的 banner 不支持随机展现,对单一文章编辑banner又太麻烦了。
于是,借助 cf 的 worker 产品,给我们的 banner 来个随机化吧。

操作

首先 你要有一个域名 挂在 Cloudflare 解析。

然后就是创建 worker 。

我只是简单的把 Hexo-Blog 部署在 cf-page 上。由于一些众所周知的原因,
我们需要把国内外的访问区分开来,不然访问图片加载太慢了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
export default {
async fetch(request) {
/**
* A map of the URLs to redirect to
* @param {Object} countryMap
*/
const countryMap = {
CN: "https://my-bucket-1301588763.cos-website.ap-guangzhou.myqcloud.com/",
OT: "https://blog.na4.top/",
};
var max=36;
var min=0;
// Use the cf object to obtain the country of the request
// more on the cf object: https://developers.cloudflare.com/workers/runtime-apis/request#incomingrequestcfproperties
const country = request.cf.country;
const pathname = 'img/' + Math.floor(Math.random()*(max-min+1)+min) + '.webp';

if (country != null && country in countryMap) {
const url = countryMap[country] + pathname;
return Response.redirect(url, 302);
} else {
const url = countryMap["OT"] + pathname;
return Response.redirect(url, 302);
}
},
};


实现随机Banner
http://blog.na4.cc/posts/682efb40/
作者
StaciaKazuha
发布于
2023年7月27日
许可协议