网站右侧边栏新增站内搜索(百度+谷歌)

网站公告站内搜索

WordPress自带的搜索功能比较简陋,研究了下使用搜索引擎作为搜索功能补充是比较合适的方式。

目前是在网站右侧新增了一个搜索框,输入关键词回车会弹出新页面展示搜索结果。

默认先读取本地缓存的用户位置区域,读取失败会通过IP判断访客位置,如果是国内就加载百度搜索,如果是境外用户就加载谷歌搜索。本地缓存有效期为1小时。

百度搜索是通过site:www.cheshirex.com空格关键词,这样的方式搜索站内内容。

谷歌搜索是使用谷歌可编程搜索引擎加载。

放置在网站右侧栏html小工具里就可以使用了。

 

 

完整代码

通过chatgpt+谷歌Gemini+deepseek+豆包等AI工具完成。

综合使用chatgpt和豆包的体验不错。

<style>
/* 使用独特前缀确保样式隔离,不影响网站其他元素 */
.cheshire-widget {
width: 100% !important;
min-width: 100% !important;
max-width: none !important;
background: rgba(255, 255, 255, 0.95);
border: none;
border-radius: 0;
box-shadow: none;
padding: 20px 0;
margin: 0 0 20px 0 !important;
box-sizing: border-box !important;
display: block !important;
float: none !important;
}

@media (max-width: 768px) {
.cheshire-widget {
padding: 15px 0;
}
}

.cheshire-title {
font-size: 18px;
font-weight: 600;
margin: 0 10px 15px 10px !important;
color: #333;
text-align: center;
}

.cheshire-form {
display: flex;
gap: 8px;
margin: 0 !important;
padding: 0 10px;
width: 100% !important;
box-sizing: border-box !important;
}

.cheshire-input {
flex: 1 1 auto !important;
padding: 10px 12px;
border: 1px solid #ddd;
border-radius: 0;
font-size: 14px;
width: 100% !important;
min-width: 0 !important;
box-sizing: border-box !important;
}

.cheshire-input:focus {
border-color: #4285f4;
outline: none;
}

.cheshire-button {
padding: 10px 16px;
background: #4285f4;
color: white;
border: none;
border-radius: 0;
cursor: pointer;
font-size: 14px;
transition: background 0.3s;
white-space: nowrap;
}

.cheshire-button:hover {
background: #3367d6;
}

.cheshire-loading {
text-align: center;
padding: 10px;
color: #666;
margin: 0 10px !important;
}

/* 确保所有内部元素样式隔离 */
.cheshire-widget * {
box-sizing: border-box !important;
}
</style>

<div class="cheshire-widget">
<div class="cheshire-title">站内搜索</div>
<div id="cheshire-container">
<div class="cheshire-loading">加载搜索服务中...</div>
</div>
</div>

<script>
// 主初始化函数
function initCheshireSearch() {
const container = document.getElementById('cheshire-container');
// 从本地缓存获取带有效期的用户区域数据
const cachedData = localStorage.getItem('cheshireSearchData');

if (cachedData) {
try {
const { region, timestamp } = JSON.parse(cachedData);
const now = Date.now();
// 验证缓存是否在1小时有效期内(1小时 = 3600000毫秒)
if (now - timestamp < 3600000) { // 此处修改为1小时
region === 'CN' ? loadBaiduSearch() : loadGoogleSearch();
return;
} else {
// 缓存过期,主动清除
localStorage.removeItem('cheshireSearchData');
}
} catch (e) {
// 缓存数据格式错误时清除
localStorage.removeItem('cheshireSearchData');
}
}

// 缓存不存在或过期时,重新检测区域
detectUserRegionByIP()
.then(region => {
if (region === 'CN') {
loadBaiduSearch();
} else {
loadGoogleSearch();
}
// 存储带时间戳的缓存数据(区域+当前时间)
localStorage.setItem('cheshireSearchData', JSON.stringify({
region: region,
timestamp: Date.now() // 记录当前时间戳(毫秒)
}));
})
.catch(() => {
// 检测失败时的安全回退(默认百度)
loadBaiduSearch();
});
}

// 仅基于IP的区域检测函数
function detectUserRegionByIP() {
return new Promise((resolve, reject) => {
// 使用IP定位API获取实际网络出口位置
fetch('https://ipapi.co/json/')
.then(res => {
if (!res.ok) throw new Error('IP检测失败');
return res.json();
})
.then(data => {
// 根据IP所在国家判断(CN=中国,其他=国际)
if (data.country === 'CN') {
resolve('CN');
} else {
resolve('INTL');
}
})
.catch(error => {
// API调用失败时的处理
console.error('IP定位失败:', error);
reject(error);
});
});
}

// 加载百度站内搜索
function loadBaiduSearch() {
const container = document.getElementById('cheshire-container');
container.innerHTML = `
<form class="cheshire-form" onsubmit="this.querySelector('.cheshire-input').value = 'site:www.cheshirex.com ' + this.querySelector('.cheshire-input').value;" action="https://www.baidu.com/s" >
<input class="cheshire-input" type="text" name="wd" placeholder="搜索本站内容..." required>
<button class="cheshire-button" type="submit">百度</button>
</form>
`;
}

// 加载谷歌站内搜索
function loadGoogleSearch() {
const container = document.getElementById('cheshire-container');
container.innerHTML = '<div class="cheshire-loading">正在加载谷歌搜索...</div>';
const script = document.createElement('script');
script.src = 'https://cse.google.com/cse.js?cx=b622f1299acbe415d';
script.async = true;
script.onload = () => {
// 谷歌自定义搜索设置为站内搜索
container.innerHTML = '<div class="gcse-searchbox-only" data-as_sitesearch="www.cheshirex.com"></div>';
};
script.onerror = () => {
container.innerHTML = '<div class="cheshire-loading">谷歌服务不可用,切换至百度...</div>';
setTimeout(loadBaiduSearch, 1500);
};
document.head.appendChild(script);
}

// 添加超时回退(2.5秒)
setTimeout(() => {
if (document.getElementById('cheshire-container').innerHTML.includes('正在加载')) {
loadBaiduSearch();
}
}, 2500);

// 页面加载完成后初始化
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initCheshireSearch);
} else {
initCheshireSearch();
}
</script>



 

Posted by 柴郡猫