酷代码 AI
菜单
服务商

JavaScript实现移动端非蜘蛛用户从搜索引擎进入插入lm.html文件

### 📋 实现思路 要实现检测是移动端用户、非蜘蛛爬虫,且是从搜索引擎点击进入,然后在当前位置插入 `lm.html` 文件,可以按以下步骤进行: 1. **检测移动端**:通过检测用户代理(User-Agent)来判断是否为移动端设备。 2. **排除蜘蛛爬虫**:通过检测用户代理中是否包含常见的爬虫关键词来排除蜘蛛爬虫。 3. **检测是否从搜索引擎进入**:检查 `document.referrer` 是否包含常见搜索引擎的域名。 4. **插入 `lm.html` 文件**:使用 `fetch` API 加载 `lm.html` 文件,并将其内容插入到当前页面的指定位置。 ### 💻 代码示例 ```javascript // 检测是否为移动端 function isMobile() { return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); } // 检测是否为蜘蛛爬虫 function isSpider() { const spiderKeywords = ['bot', 'spider', 'crawler', 'slurp']; const userAgent = navigator.userAgent.toLowerCase(); return spiderKeywords.some(keyword => userAgent.includes(keyword)); } // 检测是否从搜索引擎进入 function isFromSearchEngine() { const referrer = document.referrer; const searchEngines = ['google.com', 'baidu.com', 'bing.com']; return searchEngines.some(engine => referrer.includes(engine)); } // 插入 lm.html 文件 async function insertLmHtml() { try { const response = await fetch('lm.html'); if (response.ok) { const html = await response.text(); const div = document.createElement('div'); div.innerHTML = html; document.body.appendChild(div); } else { console.error('Failed to load lm.html:', response.status); } } catch (error) { console.error('Error loading lm.html:', error); } } // 主函数 function main() { if (isMobile() && !isSpider() && isFromSearchEngine()) { insertLmHtml(); } } // 页面加载完成后执行主函数 window.addEventListener('load', main); ``` ### 📚 代码解释 1. **`isMobile` 函数**:使用正则表达式检测用户代理中是否包含常见的移动端设备关键词。 2. **`isSpider` 函数**:检查用户代理中是否包含常见的爬虫关键词。 3. **`isFromSearchEngine` 函数**:检查 `document.referrer` 是否包含常见搜索引擎的域名。 4. **`insertLmHtml` 函数**:使用 `fetch` API 加载 `lm.html` 文件,并将其内容插入到页面的 `body` 元素中。 5. **`main` 函数**:调用上述三个检测函数,如果条件都满足,则调用 `insertLmHtml` 函数。 6. **`window.addEventListener('load', main)`**:页面加载完成后执行 `main` 函数。 ### ⚙️ 进阶使用指南 - **性能优化**:可以将 `fetch` 请求的结果进行缓存,避免重复请求。 - **错误处理**:在 `fetch` 请求失败时,除了打印错误信息,还可以进行重试或显示友好的提示信息。 - **扩展功能**:可以根据不同的搜索引擎或移动端设备类型进行不同的处理。 - **安全建议**:确保 `lm.html` 文件的来源可靠,避免加载恶意代码。 - **常见陷阱规避**:注意 `fetch` 请求的跨域问题,确保 `lm.html` 文件与当前页面在同一域名下,或者配置合适的 CORS 策略。 ### 📝 开发建议 - **兼容性**:不同浏览器对 `fetch` API 的支持可能有所不同,可以使用 `polyfill` 来确保在旧浏览器中也能正常工作。 - **调试**:在开发过程中,可以使用浏览器的开发者工具来调试代码,查看请求的状态和错误信息。 - **代码复用**:将检测函数封装成独立的模块,方便在其他项目中复用。 ### 📖 学习资源 - [MDN Web Docs - fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) - [MDN Web Docs - navigator.userAgent](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/userAgent) - [MDN Web Docs - document.referrer](https://developer.mozilla.org/en-US/docs/Web/API/Document/referrer) ######[AI写代码神器 | 1057点数解答 | 2026-05-22 00:27:36]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]