iFrame src更改事件检测?
假设我无法控制iframe中的内容,是否有任何方法可以通过父页面检测到src的变化? 某种onload可能?
我最后的手段是做一个1秒的间隔testing,如果iframe src是一样的,但做这个hacky解决scheme会吸。
如果有帮助,我正在使用jQuery库。
 您可能想要使用onLoad事件,如下例所示: 
 <iframe src="http://www.google.com/" onLoad="alert('Test');"></iframe> 
只要iframe中的位置发生变化,警报就会popup。 它适用于所有的现代浏览器,但可能不适用于一些非常老的浏览器,如IE5和早期的Opera。 ( 来源 )
  如果iframe在父级的相同域中显示页面,则可以使用contentWindow.location访问该位置,如下例所示: 
 <iframe src="/test.html" onLoad="alert(this.contentWindow.location);"></iframe> 
 $('#iframeid').load(function(){ alert('frame has (re)loaded'); }); 
 如果你没有控制页面,并希望观察某种变化,那么现代的方法是使用MutationObserver 
 使用它的一个例子,监视一个iframe的src属性的改变 
 new MutationObserver(function(mutations) { mutations.some(function(mutation) { if (mutation.type === 'attributes' && mutation.attributeName === 'src') { console.log(mutation); console.log('Old src: ', mutation.oldValue); console.log('New src: ', mutation.target.src); return true; } return false; }); }).observe(document.body, { attributes: true, attributeFilter: ['src'], attributeOldValue: true, characterData: false, characterDataOldValue: false, childList: false, subtree: true }); setTimeout(function() { document.getElementsByTagName('iframe')[0].src = 'http://jsfiddle.net/'; }, 3000); 
 <iframe src="http://www.google.com"></iframe> 
 这是在Commerce SagePay和Commerce Paypoint Drupal模块中使用的方法,它基本上比较document.location.href和旧值,方法是首先加载自己的iframe,然后加载外部的iframe。 
 所以基本上这个想法是加载空白页作为占位符与自己的JS代码和隐藏的forms。 然后,父母的JS代码将提交隐藏窗体,其#action指向外部iframe。 一旦redirect/提交发生,仍然在该页面上运行的JS代码可以跟踪你的document.location.href值的变化。 
以下是在iframe中使用的示例JS:
 ;(function($) { Drupal.behaviors.commercePayPointIFrame = { attach: function (context, settings) { if (top.location != location) { $('html').hide(); top.location.href = document.location.href; } } } })(jQuery); 
这里是用于父页面的JS:
 ;(function($) { /** * Automatically submit the hidden form that points to the iframe. */ Drupal.behaviors.commercePayPoint = { attach: function (context, settings) { $('div.payment-redirect-form form', context).submit(); $('div.payment-redirect-form #edit-submit', context).hide(); $('div.payment-redirect-form .checkout-help', context).hide(); } } })(jQuery); 
然后,在临时的空白着陆页中,您需要包含将redirect到外部页面的表单。
iframe始终保留父页面,您应该使用它来检测您在iframe中的哪个页面:
Html代码:
 <iframe id="iframe" frameborder="0" scrolling="no" onload="resizeIframe(this)" width="100%" src="www.google.com"></iframe> 
JS:
  function resizeIframe(obj) { alert(obj.contentWindow.location.pathname); }