如何实现从主页跳转至iframe内Blogger页面的指定锚点?
解决跨域iframe锚点定位问题
第一步:修改主页的链接
把主页里的链接改成指向你的restoran---jelovnik.html页面,同时带上要定位的锚点参数:
<a href="restoran---jelovnik.html#target=vecera">više >>>></a>
这样点击后会打开包含iframe的页面,而非直接跳转到Blogger的页面。
第二步:在restoran---jelovnik.html页面添加JS代码
在iframe所在的页面,添加一段JavaScript来处理URL参数,并给iframe发送定位指令:
<html> <head> <script> window.addEventListener('load', function() { // 解析URL中的锚点参数 const hashContent = window.location.hash.slice(1); const params = new URLSearchParams(hashContent); const targetAnchor = params.get('target'); if (targetAnchor) { // 获取目标iframe元素 const iframe = document.querySelector('iframe[name="restoran_jelovnik"]'); // 给iframe发送跨域消息,指定要滚动到的锚点 iframe.contentWindow.postMessage({ action: 'scrollToAnchor', anchor: targetAnchor }, 'https://caravaggiorestoran.blogspot.com'); } }); </script> </head> <body> <iframe src="https://caravaggiorestoran.blogspot.com/p/caravaggio-restoran-jelovnik.html" style="border: 0px none rgb(255, 255, 255); height: 7137px;" name="restoran_jelovnik" onload="javascript:(function(o){o.style.height=o.contentWindow.document.body.scrollHeight+"px";}(this));" scrolling="no" frameborder="0" marginheight="0px" marginwidth="0px" height="200px" width="100%" allowfullscreen=""></iframe> </body> </html>
注意:postMessage的第二个参数要准确填写Blogger页面的域名,避免安全风险。
第三步:在Blogger页面添加监听代码
打开Blogger页面的HTML视图,在<head>标签内添加以下JS代码,用来接收消息并触发锚点滚动:
<script> window.addEventListener('message', function(event) { // 验证消息来源,仅处理来自你主站的消息 if (event.origin !== '你的主站域名') return; if (event.data.action === 'scrollToAnchor') { const anchorElement = document.getElementById(event.data.anchor); if (anchorElement) { // 滚动到目标锚点位置 anchorElement.scrollIntoView({ behavior: 'smooth' }); } } }); </script>
将你的主站域名替换为你用Nicepage搭建的网站域名(例如https://your-restaurant-site.com),防止恶意网站发送非法消息。
原方案失效原因
你的主站与Blogger属于不同域名,浏览器的同源策略会禁止直接操作跨域iframe的内容,也不支持通过target指向iframe加载带锚点的跨域页面。必须用postMessage实现跨域通信,间接触发锚点滚动。
内容的提问来源于stack exchange,提问作者Igor
相关产品推荐
相关产品推荐

