在具有跨域站点但位置相同的 JS 文件的子 iFrame 中调用 Javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5797117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:22:55  来源:igfitidea点击:

Call Javascript Function in Child iFrame with Cross Domain site but Same location JS file

javascripthtmlbrowseriframecross-domain

提问by drt

I am trying to do the following:

我正在尝试执行以下操作:

Main document calls a function in iFrame whose URL is from a different locationbut the Javascript function I'm trying to call loaded from the same domain as the main document.

主文档调用 iFrame 中的一个函数,其URL 来自不同的位置,但我试图调用的 Javascript 函数从与主文档相同的域加载。

Is there any way to do this?

有没有办法做到这一点?

To clarify:

澄清:

  • Main document: http://www.main.com
  • iFrame document: http://www.example.com
  • JS function i'm calling in iFrame is at http://www.main.com/js/script.js
  • 主文档:http: //www.main.com
  • iFrame 文档:http: //www.example.com
  • 我在 iFrame 中调用的 JS 函数位于http://www.main.com/js/script.js

I'm getting

我越来越

Permission denied to access property 'js_function'

When doing

做的时候

document.getElementById("iframe").contentWindow.js_function(n)

采纳答案by Christian

I see what you're doing. There was a "hack" that made use of two iframes (if I remember correctly). Both that hack and the one you mention here are awfully obscure, and I wouldn't be surprised if they have been locked down knowingly.

我明白你在做什么。有一个“hack”使用了两个 iframe(如果我没记错的话)。那个 hack 和你在这里提到的那个都非常晦涩,如果它们被故意锁定,我不会感到惊讶。

The best fix I can think of is to load the code for js_function()in the main window (outside of the iframe).

我能想到的最佳解决方法是js_function()在主窗口(iframe 之外)加载代码。

Can you be more specific on what the JS code does? I may be able to help better.

你能更具体地说明 JS 代码的作用吗?我也许能更好地提供帮助。

回答by Sean Vieira

Even though the script is hosted on main.comit is executedin the context of example.comand therefore is considered to be part of example.com... and therefore has no access to variables or functions in the main.comwindow. You can hack around this with variouscrossdomaincommunicationhacks (or you can ignore IE < 8 and use window.postMessageby itself).

即使脚本托管在main.com它的上下文中执行example.com,因此被认为是example.com...的一部分,因此无法访问main.com窗口中的变量或函数。你能砍解决此用各种通信黑客(或者你可以忽略IE <8,并利用window.postMessage本身)。

SEE ALSO: http://stevehanov.ca/blog/index.php?id=109

另见:http://stevehanov.ca/blog/index.php?id= 109

回答by Sean Kinsey

Use easyXDM'sRPC feature, it combines XDM with RPC. An example of this can be seen here: http://consumer.easyxdm.net/current/example/methods.html

使用easyXDM的RPC特性,它结合了XDM和RPC。一个例子可以在这里看到:http: //consumer.easyxdm.net/current/example/methods.html