通用跨域解决方案(通过 localStorage 通信)

1、需要在父页面添加监听事件

1.1父页面代码(parent.html)

在父页面添加监听事件,来监听 localStorage 中的 needRefresh值;

<script>
// 监听存储事件
window.addEventListener('storage', (event) => {
  if (event.key === 'needRefresh' && event.newValue === 'true') {
    location.reload();
    localStorage.removeItem('needRefresh'); // 清除标记
  }
});
</script>

2、子压面存储时间标识,并关闭当前页面

2.1 子页面代码(child.html)

在子页面中,当点击保存按钮,保存成功以后,首先 在localStorage 中将needRefresh设置为true;然后,在关闭当前页面,就会自动回到父页面,并且刷新父页面。

<button class="btn btn-warning" id="saveButton">保存并关闭</button>

<script>
document.getElementById('saveButton').addEventListener('click', async () => {
  // 执行保存操作
  const success = await fetch('/api/save', { method: 'POST' }).then(res => res.ok);

  if (success) {
    try {
      closeCuurrTable();
    } catch {
      // 4. 失败时引导返回
      alert('操作成功,即将返回原页面');
      window.history.go(-1); // 或 location.href = 父页面URL
    }
  }
});

    // 关闭当前页
    function closeCuurrTable(){
        // 通过存储事件通知父页面
        localStorage.setItem('needRefresh', 'true');
        // 关闭当前tab页
        var _cnt = window.parent.defaultCnt;
        _cnt.closeTab();
    }
</script>

注:记录工作中遇到的问题及解决方案,大家有更优的解决方案,欢迎补充!

Logo

中国智能体开发者社区,聚焦智能体与大模型开发,提供前沿资讯、实用工具链、开源项目及行业案例。通过技术沙龙、开发者大赛等活动,促进经验交流与协作,助力开发者快速构建创新智能应用。

更多推荐