重新加载iframe后无法访问父页面

Can't access parent page after reloading iframe

要从 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 中看到的情况,jQuery 会在每次从 iframe 重新加载时加载,我猜有些 variables/triggers 在第一次加载后仍然处于活动状态?在 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

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

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

务必将所有按钮选择器添加到一个数组中,例如:

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