如何从嵌入Google Sites的Google Apps Script导航栏实现页面跳转
问题根因
Google Apps Script 发布的Web App嵌入Google Sites后,平台会给Web App的iframe自动加上沙箱限制,默认未开放allow-top-navigation、allow-top-navigation-by-user-activation权限,所以直接使用target="_top"触发顶层页面跳转时会被浏览器安全策略拦截,和你控制台输出的报错一致。而无target属性的链接默认在当前iframe打开,Google Sites本身设置了X-Frame-Options禁止被嵌入第三方iframe,所以会报refused to connect。
开发者无法通过修改GAS服务端的setSandboxMode、setXFrameOptionsMode参数变更平台预设的沙箱权限,所以直接用a标签target属性实现顶层跳转的方案走不通。
可行解决方案
方案1:通过postMessage跨iframe通信实现顶层跳转
这是目前唯一可以实现同窗口整页跳转的方案,修改步骤如下:
- 修改GAS前端代码
nawigacja.html,给所有需要整页跳转的a标签添加自定义标识(比如class为top-nav),同时在页面末尾插入跳转事件监听脚本:
<!-- 修改你的跳转链接 --> <a href="https://sites.google.com/" class="top-nav">跳转链接</a> <!-- 插入在</body>标签之前 --> <script> document.querySelectorAll('.top-nav').forEach(navLink => { navLink.addEventListener('click', function(e) { e.preventDefault(); const jumpUrl = this.getAttribute('href'); window.parent.postMessage({ action: 'siteJump', url: jumpUrl }, '*'); }) }) </script>
- 打开你嵌入导航栏的Google Sites编辑页,在页面任意位置插入一个「内嵌代码」块,粘贴如下消息接收脚本:
<script> window.addEventListener('message', function(e) { // 校验消息来源为GAS Web App域名,避免安全风险 if(e.origin.endsWith('script.googleusercontent.com') && e.data.action === 'siteJump') { window.location.href = e.data.url; } }) </script>
修改完成后重新发布GAS Web App、发布Google Sites页面即可生效。
方案2:继续使用target="_blank"新开页跳转
如果不需要同窗口跳转,你已经验证过的target="_blank"方案是最简便的可用方案,无需额外修改其他代码。
内容的提问来源于stack exchange,提问作者Abdel5
相关产品推荐
相关产品推荐

