0

我在 javascript 方面有点菜鸟,所以请帮帮我。我的身体标签底部有这个:

<iframe id="scriptFrame" name="scriptFrame" height="0" width="0">
<script type="text/javascript" language="javascript">
alert("Hello World");
parent.alert("Hello world");
function foo()
{
   alert("Hello World");
}
</script>
</iframe>

两个警报都不会弹出。我究竟做错了什么?我尝试添加 html 和 head 标签,但没有帮助。我也尝试过 document.getElementById('scriptFrame').contentWindow.foo() 和 frames['scriptFrame'].foo() 但都没有奏效

4

5 回答 5

2

请注意,您不能将任何内容直接添加到<iframe>标签中。即使使用 JavaScript,您也只能在 iframe 中的页面与父页面来自同一个域时添加内容。因此,您必须执行以下操作:

<html>
<body>
<script >
function foo()
{
   alert("Hello World");
}
</script>
<iframe id="scriptFrame" onload="foo()"name="scriptFrame" height="0" width="0"> 
</iframe>
</body>
</html>

从 iframe 调用父 JS 函数是可能的,但只有当 iframe 中加载的父页面和页面都来自同一个域,即 abc.com,并且两者都使用相同的协议,即两者都在 http:// 或 https 上时: //。

在以下提到的情况下,调用将失败:

  1. 父页面和 iframe 页面来自不同的域。

  2. 他们使用不同的协议,一种在 http:// 上,另一种在 https:// 上。

对此限制的任何解决方法都将非常不安全。

例如,假设我注册了域 superwinningcontest.com 并发送了指向人们电子邮件的链接。当他们加载主页时,我可以在其中隐藏一些 iframe 并阅读他们的 Facebook 提要,检查最近的 Amazon 或 PayPal 交易,或者——如果他们使用的服务没有实现足够的安全性——将资金从他们的帐户。这就是 JavaScript 仅限于同域和同协议的原因。

于 2013-02-14T15:26:16.260 回答
1

iframe 的内容永远不会被渲染。在 iframe 内指定某些内容时,这是使用 src 属性加载的内容的后备(对于不支持 iframe 的浏览器)。

因此,要么对 iframe 使用 onload,要么将 iframe 的内容放在单独的页面中,并在 src-attribute 中指定。

于 2013-02-14T15:29:47.587 回答
1

您必须将 iframe 的 src 属性与 iframe 将加载其内容的 URI 一起使用。

要内联插入的信息由该元素的 src 属性指定。另一方面,IFRAME 元素的内容只能由不支持框架或配置为不显示框架的用户代理显示。

您在 iframe 标记内有脚本,因此它只会在不支持框架的浏览器上显示。

于 2013-02-14T15:29:57.830 回答
0

您必须<html>在 iframe 中,并且<script>标签必须在<head>或 中<body>

另外,请注意不推荐使用的language属性。<script>

于 2013-02-14T15:08:07.980 回答
0

如果您在加载 iframe 时尝试运行 javascript,请尝试以下操作:

<html>
    <head>
        <script type="text/javascript">
            function someFunction(){
                //some stuff here
            }
        </script>
    </head>
    <body>
        <iframe id="scriptFrame" name="scriptFrame" height="0" width="0" onload="someFunction();"></iframe>
     </body>
</html>
于 2013-02-14T15:24:26.463 回答