【问题标题】:Capture iFrame onhashchange event from the parent从父级捕获 iFrame onhashchange 事件
【发布时间】:2017-04-22 01:09:53
【问题描述】:

我试图从他的父母那里捕获 iFrame 的 onHashChange 事件,但没有成功。

所以基本上我在做:

index.html - 方法 1:

iframeEl = document.getElementById('myiframeid');
iframeEl.addEventListener('hashchange', function() {
    alert('hash changed')
}, true);

index.html - 方法 2:

iframeEl = document.getElementById('myiframeid');
iframeEl.onhashchange = function() {
    alert('hash changed')
};

无论如何,当我尝试从他的父级捕获 iframe 事件时,这些方法都不起作用,尽管如果我尝试从 iframe 内部运行以下代码:

window.addEventListener('hashchange', function() {
    alert('hash changed')
}, true);

window.onhashchange = function() {
    alert('hash changed')
};

这两种方法都可以。

问题是:我需要从 iFrame 外部捕获 hashchange 事件。

有人知道如何处理吗?

仅供参考:jQuery 不是一个选项。

提前致谢。

【问题讨论】:

  • 您需要IframeElement.contentWindow.documentIframeElement.contentDocument。第一个是向后兼容的。 chage 事件需要附加到作为 IframeElement.contentDocument 一部分的特定元素。
  • 您好,感谢您的回答,不幸的是它没有工作。我用两种方法(上面)尝试了你的两个建议,但什么也没发生。您是否介意将您的想法放入 fiddlejs 或类似的东西中?谢谢
  • 两个页面是否在同一个域中?
  • 是的!他们是。实际上两者都是本地主机。 :)
  • 哦,那是onchashchage。等等。

标签: javascript html events iframe hashchange


【解决方案1】:

假设您想从包含您的<iframe> 的页面测试IframeElement.contentWindow 上的哈希更改:

//<![CDATA[
// external.js - the page with your <iframe>
var doc, bod, htm, C, E, T; // for use on other loads
addEventListener('load', function(){ // window.onload sort of

doc = document; bod = doc.body; htm = doc.documentElement;
C = function(tag){
  return doc.createElement(tag);
}
E = function(id){
  return doc.getElementById(id);
}
T = function(tag){
  return doc.getElementsByTagName(tag);
}
var innerWindow = E('yourIframeId').contentWindow;
var oldHash = innerWindow.location.hash.replace(/#/, '');
innerWindow.addEventListener('hashchange', function(){
  console.log('#'+oldHash+' has been changed to #'+innerWindow.location.hash.replace(/#/, ''));
});

}); // end load
//]]>

【讨论】:

  • 我想我可能表达得很糟糕。基本上,每次 iframe 中的哈希更改时,我都希望在父元素级别捕获。哈希我的意思是
  • 但是,非常感谢您的努力 :)
  • 所以您要更改IframeElement.src 而不是IframeElement.contentWindow?没有事件可以查看src 是否已更改。更改 IframeElement.src 将重新加载页面。只需使用innerWindow.location.hash = 'hashWithoutPound' 更改哈希,基于上面代码中的innerWindow
  • @TitoFacchini src 变化如何?
猜你喜欢
  • 1970-01-01
  • 2015-06-13
  • 2014-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-08
  • 1970-01-01
相关资源
最近更新 更多