如何通过URL附加参数实现iframe自动加载指定历史博客文章
实现方案
步骤1:修改iframe标签,添加id属性
给现有的iframe加上id属性,方便JavaScript定位元素,原有功能不受影响,修改后的代码如下:
<div class="blog"> <iframe src="Blogs/REVblog20211023.html" name="myBlogFrame" id="myBlogFrame" scrolling="yes"></iframe> </div>
步骤2:页面添加自动加载逻辑代码
在页面的</body>闭合标签之前插入以下JavaScript代码即可:
window.onload = function() { // 提取URL中#后的锚点内容 const hashContent = window.location.hash.slice(1); // 校验锚点是否是指定的iframe跳转格式 if (hashContent.startsWith('iframe:')) { const targetBlogPath = hashContent.split('iframe:')[1]; // 额外校验路径,仅允许加载本站Blogs目录下的内容,避免安全风险 if (targetBlogPath.startsWith('Blogs/')) { document.getElementById('myBlogFrame').src = targetBlogPath; } } }
功能说明
部署完成后,访问符合https://你的域名/blog.html#iframe:博客文件路径格式的链接,就会自动在iframe中加载对应博客内容。你原有历史博客的跳转逻辑、每周手动更新默认iframe src的操作都不需要修改,不受任何影响。
内容的提问来源于stack exchange,提问作者Roxana
相关产品推荐
相关产品推荐

