Blogger中执行成功后结果自动消失的问题:请求将代码修改为静态以固定展示结果
Blogger中执行成功后结果自动消失的问题:请求将代码修改为静态以固定展示结果
我看了你的代码,发现问题大概率出在JSONP异步请求的回调顺序或者未正确终止后续查找逻辑上——即使你是串行发起关键词匹配请求,也可能因为网络延迟、Blogger的页面动态特性,导致已渲染的匹配内容被意外覆盖或重置。
要让结果静态固定不消失,咱们做几个关键优化:
- 一旦找到匹配的博客文章,立刻终止后续所有关键词的匹配请求,彻底避免内容被覆盖
- 优化JSONP的回调和资源清理逻辑,减少意外操作DOM的可能
- 新增状态标记,确保匹配结果一旦渲染就不会被后续代码修改
下面是修改后的完整代码,直接替换你原来的代码即可:
<div id="user-country">Detecting your country...</div> <div id="trending-topics"> <h3>Trending Topics</h3> <ul id="trending-list">Loading...</ul> </div> <div id="matchedPost">Loading...</div> <script> async function detectCountry() { try { const res = await fetch('https://ipapi.co/json/'); const data = await res.json(); const countryCode = data.country; // e.g., "IN" const countryEl = document.getElementById('user-country'); if (countryEl) { countryEl.innerText = "You are visiting from: " + countryCode; } return countryCode; } catch(err) { const countryEl = document.getElementById('user-country'); if (countryEl) { countryEl.innerText = "Could not detect country"; } console.error(err); return "US"; // fallback country } } async function fetchTrending(countryCode) { const RSS_URL = `https://trends.google.com/trending/rss?geo=${countryCode}`; const listEl = document.getElementById("trending-list"); if (!listEl) return []; listEl.innerHTML = ""; try { const response = await fetch(`https://api.rss2json.com/v1/api.json?rss_url=${encodeURIComponent(RSS_URL)}`); const data = await response.json(); const trendingTags = []; data.items.forEach(item => { const li = document.createElement("li"); li.innerHTML = `<a href="${item.link}" target="_blank">${item.title}</a>`; listEl.appendChild(li); trendingTags.push(item.title); // collect titles for blog search }); return trendingTags; } catch (error) { console.error("Error fetching trending topics:", error); listEl.innerHTML = "<li>Failed to load trends.</li>"; return []; } } function fetchBlogPost(tags) { const blogURL = "https://artisthindustani.blogspot.com"; // your blogspot URL const matchedPostEl = document.getElementById("matchedPost"); if (!matchedPostEl) return; // 新增状态标记:是否已找到匹配文章,防止后续请求覆盖内容 let isPostFound = false; function fetchPostByKeyword(keyword, onSuccess, onFail) { if (isPostFound) return; // 已找到结果,直接终止当前请求 const callbackName = "cb_" + Date.now() + "_" + Math.floor(Math.random()*1000); window[callbackName] = function(data) { try { if (!isPostFound && data.feed?.entry?.length > 0) { const entry = data.feed.entry[0]; const title = entry.title.$t; const link = entry.link.find(l => l.rel === "alternate").href; let imgURL = ""; if (entry["media$thumbnail"]) { imgURL = entry["media$thumbnail"].url; } else { const htmlContent = entry.content?.$t || entry.summary?.$t || ""; const imgMatch = htmlContent.match(/<img[^>]+src="([^">]+)"/i); if (imgMatch) imgURL = imgMatch[1]; } const imgHTML = imgURL ? `<img src="${imgURL}" alt="${title}" style="max-width:100%;margin-top:8px;">` : ""; // 渲染匹配结果 matchedPostEl.innerHTML = `<h3><a href="${link}" target="_blank">${title}</a></h3>${imgHTML}`; isPostFound = true; // 标记为已找到,终止后续所有查找 onSuccess?.(); } else { onFail?.(); } } catch (err) { console.error("Error processing blog post:", err); onFail?.(); } finally { // 安全清理回调和script标签 delete window[callbackName]; const scriptEl = document.querySelector(`script[src*="${callbackName}"]`); if (scriptEl && scriptEl.parentNode) { scriptEl.parentNode.removeChild(scriptEl); } } }; const script = document.createElement("script"); script.src = `${blogURL}/feeds/posts/default?q=${encodeURIComponent(keyword)}&alt=json-in-script&max-results=1&callback=${callbackName}`; document.body.appendChild(script); } function findFirstMatch(index) { // 已找到结果或无更多关键词,终止 if (isPostFound || index >= tags.length) { if (!isPostFound) { matchedPostEl.innerHTML = "No matching blog found."; } return; } fetchPostByKeyword(tags[index], () => {}, () => findFirstMatch(index + 1)); } findFirstMatch(0); } // Main integration (async function() { const countryCode = await detectCountry(); const trendingTags = await fetchTrending(countryCode); if (trendingTags.length > 0) { fetchBlogPost(trendingTags); } else { const matchedPostEl = document.getElementById("matchedPost"); if (matchedPostEl) { matchedPostEl.innerHTML = "No trending topics available to match."; } } })(); </script>
关键修改说明:
- 新增
isPostFound状态标记:一旦找到匹配的博客文章,立刻将该标记设为true,后续所有的关键词匹配请求都会直接终止,从根源上避免内容被覆盖。 - 优化DOM元素检查:所有对DOM元素的操作前都先检查元素是否存在,减少意外报错导致的逻辑中断。
- 改进JSONP清理逻辑:通过
querySelector精准定位要删除的script标签,避免误删其他元素,同时用try...finally确保回调和资源一定会被清理。 - 增强终止逻辑:在
findFirstMatch中先检查isPostFound状态,确保已找到结果后不再执行后续查找。
这样修改后,匹配的博客文章内容会被静态固定在页面上,不会再自动消失。
内容来源于stack exchange
相关产品推荐
相关产品推荐

