【问题标题】:Can't access parent page after reloading iframe重新加载 iframe 后无法访问父页面
【发布时间】:2021-09-03 00:24:39
【问题描述】:

要从 iframe 中访问父网站,我使用“parent.document”。这是一个例子:

$('.my-plugin', parent.document).addClass('is-active');

这很好用。

但是,如果我重新加载 iframe,它就不再工作了。脚本加载,但每当我运行任何“parent.document”代码时都会失败,在 DevTools 中出现此错误:

Uncaught TypeError: Cannot read property 'document' of null
at HTMLDivElement.<anonymous> (VM28598 app.js:720)

从我在 DevTools 中可以看到,每次从 iframe 重新加载时,jQuery 都会加载,我的猜测是某些变量/触发器在第一次加载后仍然处于活动状态?在 DevTools 中看起来像这样:

Script: jquery-3.5.1.min.js Initaiator: app.js:663 //after first load
Script: jquery-3.5.1.min.js Initiator: VM28598 app.js:663 //after second load, etc

【问题讨论】:

  • 这个问题很可能是由于手动刷新子 iframe 时引荐来源丢失,这控制了内容的可访问性限制。没有解决方法。如果您需要更新 iframe 中的内容,则需要使用 AJAX 来避免重新加载页面(并且通过代理丢失引荐来源标头)
  • 感谢您的评论。是否有参考/搜索短语,所以我可以搜索任何解决方案?我无法控制父 iframe 或子 iframe(只有 iframe 中的一个脚本),所以很遗憾,我认为您的建议对我来说是不可能的。

标签: javascript jquery iframe


【解决方案1】:

我通过取消绑定点击监听器解决了这个问题:

$(window).on('unload', function() {
  for (var i = 0; i < parentUnbindOnRefresh.length; i++) {
    $(document).off('click', parentUnbindOnRefresh[i]);
  }
});

确保将所有按钮选择器添加到数组中,例如:

parentUnbindOnRefresh = ['.back-button', '.bar-open', '.type-color'];

【讨论】:

    猜你喜欢
    • 2013-12-28
    • 2023-03-31
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    • 2014-09-23
    相关资源
    最近更新 更多