帧源变化检测

Frame Source change detection

我有以下代码:

<div class="row">
<div>
    <iframe id="myFrame" name="myFrame" class="btn-block" ng-src="{{myframeSrc | trusted}}" onLoad="contentChanged()" scrolling="no"></iframe>
</div>

<script type="text/javascript">
var contentChanged = function() {
    alert('frame content has changed');
};
</script>

我知道这应该有效(确实如此),因为警报会弹出。但是,我收到 [Uncaught ReferenceError: contentChanged is not defined] 错误。我究竟做错了什么?注意:我正在通过 Angular 加载 src,但需要纯 javascript 来检测当在 iFrame 内的 Angular 之外单击 link 时帧源发生变化。

尝试用调用匿名函数的 var 语句替换函数声明。参见 var functionName = function() {} vs function functionName() {}, What's the difference in those declarations (in JavaScript)?

<script type="text/javascript">
function contentChanged() {
    alert('frame content has changed');
};
</script>
<div class="row">
<div>
    <iframe id="myFrame" name="myFrame" class="btn-block" ng-src="{{myframeSrc | trusted}}" onLoad="contentChanged()" scrolling="no"></iframe>
</div>

我的猜测是,由于 <iframe><script> 之前,所以它在 <script> 之前加载。

稍后,<script> 被加载,angular 最终加载并更新 <iframe>src 属性,这导致 <iframe>重新加载并 运行 您的 onLoad 中的代码。

要证实这个理论,试试这个:

<div class="row">
<div>
    <iframe id="myFrame" name="myFrame" class="btn-block" ng-src="{{myframeSrc | trusted}}" onLoad="console.log('iframe loaded'); contentChanged()" scrolling="no"></iframe>
</div>

<script type="text/javascript">
console.log('script tag is being executed');
var contentChanged = function() {
    console.log('contentChanged() is being executed');
    alert('frame content has changed');
};
</script>

您应该可以在您的控制台中按此顺序看到输出(您可能在 angular 或您的其他代码之间有其他行):

iframe loaded

[Uncaught ReferenceError: contentChanged is not defined]

script tag is being executed

iframe loaded

contentChanged() is being executed

window.frames - 允许直接访问 iframe window 对象。

frames.onload = function() {
    alert('frame content has changed')
 };

http://codepen.io/nagasai/pen/jrybgN

另一种选择是 document.getElementsByTagName onload document.getElementsByTagName('iframe')[0].onload = function() { 警报('frame content has changed') };

代码笔:http://codepen.io/nagasai/pen/gMgaJd

您的代码片段完全正确。唯一的错误是您声明的方式及其由于 JavaScript 变量提升。

您的代码应该如下所示。

<script type="text/javascript">
function contentChanged() {
    alert('frame content has changed');
};
</script>

<div class="row">
<div>
    <iframe id="myFrame" name="myFrame" class="btn-block" src="http://www.w3schools.com" onLoad="contentChanged()" height="400"></iframe>
  
</div>

The difference is in your function is only defined when that line is reached, whereas above function is defined as soon as its surrounding function or script is executed, due to hoisting.

参考这个简单的例子 - http://www.w3schools.com/js/js_hoisting.asp