【问题标题】:How to call function in main window from iframe?如何从 iframe 调用主窗口中的函数?
【发布时间】:2013-03-15 11:18:05
【问题描述】:

首先,我知道这个问题与其他问题重复。但是我尝试从stackoverflow中的许多问题中跟踪许多样本,但它没有用。我无法从 iframe 调用主窗口的功能,但如果我使用框架标签,它就可以工作。

我试过这样。

主窗口:

<body>
<iframe src='test.html'></iframe>
<script>            
    var alertFunc = function(){
        window.alert("work!");
    }   
</script>
</body>

test.html

<body>
    <input type="button" onclick="window.parent.alertFunc();" value="Test" />
</body>

来自控制台的错误消息。

Unsafe JavaScript attempt to access frame with URL file:///C:/.../index.html from frame with URL file:///C:/.../test.html. Domains, protocols and ports must match.
 test.html:30
Uncaught TypeError: Cannot call method 'alertFunc' of undefined 

还有很多类似的形式。

你有什么想法吗?还是我做错了什么?

【问题讨论】:

  • 检查您的浏览器控制台是否有任何错误
  • @Arun P Johny 错误已更新
  • 这是因为same origin policy,如果您将站点部署在tomcat或任何其他Web服务器中,而不是从本地文件系统访问它应该可以工作

标签: javascript html function iframe frame


【解决方案1】:

看起来您正在直接从文件系统访问文件,例如 c:.....\page.html。

由于same origin policy 导致的错误,如果您将站点部署在 tomcat 或任何其他 Web 服务器中,而不是从本地文件系统访问它,它应该可以工作,假设这两个文件来自同一个域空间。

如果主页面(带有 iframe)和 iframe 页面在同一目录中,或者如果 iframe 页面是主页面目录的子目录,它将在FireFox 中工作。

以上内容不适用于 chrome 你需要 start chrome with the flag --allow-file-access-from-files

【讨论】:

  • 但我将此应用程序设置为离线应用程序。我该如何解决这个问题?
  • 使用的是哪个浏览器?
  • 尝试用上面的标志启动chrome并测试它
  • 我已经试过了。我没有在 Chrome 上工作,但在 Firefox 上工作。我在 Windows cmd 上运行像这样的“chrome.exe --allow-file-access-from-files”的 chrome。这是正确的。不是吗?
  • 它对我有用,这是使用的 os 和 chrome 版本
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-10
  • 2017-06-20
  • 1970-01-01
  • 2013-10-24
  • 2014-11-29
  • 1970-01-01
相关资源
最近更新 更多