Shiro open-source version supports random hitokoto on the homepage
Cause
Today, I originally planned to add the hitokoto feature to the Shiro theme, but guess what? This feature is only supported by the closed-source version. Hmm, a bit stingy, right? But, there is a way to solve this.
image-20250307111205841
Solution?
It's easy.
Principle
The Shiro theme allows injecting JS scripts, so let's approach it from here.
image-20250307111321633
Create the JS script
Create a JS file under your own CDN.
// The following is for replacing the default hitokoto on the Shiro theme homepage.
// Check if the current page is the homepage
if (window.location.pathname === '/' || window.location.pathname === '/index.html') {
// Delay execution for 0.5 seconds
setTimeout(() => {
// Use fetch to request data
fetch('https://v1.hitokoto.cn')
.then(response => {
// Check if the response is successful
if (!response.ok) {
throw new Error('Network response failed');
}
return response.json(); // Parse JSON data
})
.then(data => {
// Get the target element
const hitokotoElement = document.querySelector('small.text-center');
if (hitokotoElement) {
// Replace the content of the element with the retrieved sentence
hitokotoElement.innerText = data.hitokoto;
console.log('Default hitokoto replaced');
}
})
.catch(error => {
console.error('Request failed:', error);
});
}, 500); // 500 ms = 0.5 seconds
}
Introduce the file
Introduce this JS file. For example, mine is https://fastly.jsdelivr.net/gh/sysfox/cdn/blog/custom.js
(Note: This script includes my custom functionality, so it's recommended to write your own JS)
Introduce it in the backend:
image-20250307111753421
(Please make sure it follows JSON syntax)
Check
Vercel deployment might have cache, so you may need to wait for a while.
Effect
image-20250307111919572
Console output
image-20250307112003330