javascript - 无法在跨域环境中访问 JS 功能

标签 javascript iframe

为了解决JavaScript的跨域安全问题,我实现了以下方法

在域 [ abc.com ] 上

在域 abc.com 上,我有一个名为 main_page.html 的页面。其代码如下——

<script>
function SendMsg(id)
{
   frames["invisible_iframe"].location = "http://xyz.com/invisible_iframe.html#"+id;
}
</script>
<body>
  <input type="button" id="Test" value="Call iFrame" onclick="SendMsg(this.id);">
  <iframe src="ttp://xyz.com/visible_iframe.html" name="visible_iframe" height="250" width="500"></iframe>
  <iframe name="invisible_iframe" height="0" width="0" style="display:none;"></iframe>
</body>

在域 [ xyz.com ] 上

在域 xyz.com 上,我有一个名为 visible_iframe.html 的页面。其代码如下——

<script>
function Hi()
{
   alert("Hi there!");
}
</script>
<body>
  <h1>Visible iFrame on xyz.com
  <iframe name="d2_invisible_iframe" id="d2_invisible_iframe" class="iFrame" src="http://xyz.com/invisible_iframe.html" height="310" width="520"></iframe>
</body>

现在我想从 invisible_iframe.html(在同一个域中)访问函数 Hi()

invisible_iframe.html代码如下

<script>
var sActionText = "";
function CheckForMessages()
{
   if(location.hash != sActionText)
   {
     sActionText = location.hash;
     var sAction = "";
     var oSplitActionText = sActionText.split("#");
     sAction = oSplitActionText[1];
     if (sAction == "Test")
     {
        parent.Hi();
     }
   }
}

setInterval(CheckForMessages, 200); 
</script>
<body>
  <h1>Invisible iFrame on xyz.com</h1>
</body>

我在 visible_iframe.html 中使用隐藏的 iFrame,因为我不想更改 visible_iframe.html 的 URL。

现在我希望当单击 main_page.html 上的按钮时,我会收到警告消息。但那不会发生。在 Firefox 中它说 - Permission denied to access property 'Hi'

奇怪的是当我把parent.Hi();放在CheckForMessages()函数外面时,Hi()函数可以访问并显示警告框。

我应该怎么做才能解决这个问题?

最佳答案

为什么不使用 easyXDM ?这个库应该让你的生活变得非常轻松,并有助于在处理跨域问题时避免安全限制。特别是如果您可以控制这两个域。

easyXDM is a Javascript library that enables you as a developer to easily work around the limitation set in place by the Same Origin Policy, in turn making it easy to communicate and expose javascript API’s across domain boundaries.

[这是最好且易于使用的 API 之一] 可用于 Web 应用程序之间的跨域通信。 easyXDM 易于使用、重量轻、灵活、编写高质量代码等。我强烈认为,如果您要继续使用跨域方案,那么您应该采用强大的跨域 api,例如 easyXDM .

[easyXDM 与 PostMessage 传输?] 如果浏览器(IE8+、Opera 9+、Firefox 3+、Safari 4+、Chrome 2+)启用了此功能,easyXDM 将使用 PostMessageTransport 方法;另一方面,它将为不支持的浏览器使用不同的传输方法例如(Firefox 1-2 - 使用 FrameElementTransport)其他传输方法将根据需要使用,例如 FlashTransport、NameTransport 和 HashTransport。

这显然使 easyXDM 在浏览器支持方面更胜一筹,尤其是对旧浏览器的支持。


使用 easyXDM 演示跨域访问(域 1 [abc.com] 调用远程域 [xyz.com] 上的方法):


*域 [ abc.com ] - 主域*

    <script type="text/javascript">
        /**
         * Request the use of the JSON object
         */
        easyXDM.DomHelper.requiresJSON("../json2.js");
    </script>
    <script type="text/javascript">
        var remote;
        window.onload = function(){
            /**
             * When the window is finished loading start setting up the interface
             */
            remote = new easyXDM.Interface(/** The channel configuration */{
                /**
                 * Register the url to hash.html, this must be an absolute path
                 * or a path relative to the root.
                 * @field
                 */
                local: "/hash.html",
                /**
                 * Register the url to the remote interface
                 * @field
                 */
                remote: "http://YOUR.OTHER.DOMAIN/YOUR_APPLICATION/YourRemoteApplication.html",
                /**
                 * Register the DOMElement that the generated IFrame should be inserted into
                 */
                container: document.getElementById("embedded")
            }, /** The interface configuration */ {
                remote: {
                    remoteApplicationMethod: {},
                    noOp: {
                        isVoid: true
                    }
                },
                local: {
                    alertMessage: {
                        method: function(msg){
                            alert(msg);
                        },
                        isVoid: true
                    }
                }
            },/**The onReady handler*/ function(){
                /**
                 * Call a method on the other side
                 */
                remote.noOp();
            });
        }

        function callRemoteApplicationMethod(Value1, Value2){
            remote.remoteApplicationMethod(Value1, Value2, function(result){
                alert("Results from remote application" + result);
            });
        }


    </script>

在体内

<input type="button" onclick="callRemoteApplicationMethod(3,5)" value="call remoteApplicationMethod on remote domain"/>

现在在您的远程域端,您需要按如下方式定义您的远程客户端

*域 [ xyz.com ] - 远程域*

这应该进入页面 YOUR_APPLICATION/YourRemoteApplication.html

    <script type="text/javascript">
        /**
         * Request the use of the JSON object
         */
        easyXDM.DomHelper.requiresJSON("../json2.js");
    </script>
    <script type="text/javascript">
        var channel, remote;
        /**
         * When the window is finished loading start setting up the channel
         */
        window.onload = function(){

            /**
             * When the channel is ready we create the interface
             */
            remote = new easyXDM.Interface(/** The channel configuration*/{}, /** The configuration */ {
                remote: {
                    alertMessage: {
                        isVoid: true
                    }
                },
                local: {
                    remoteApplicationMethod: {
                        method: doSomething(value1, value2){
                        // do somethigs with values

                        return "i'm return value from remote domain";
                        }
                    },
                    noOp: {
                        isVoid: true,
                        method: function(){
                            alert("Method not returning any data");
                        }
                    }
                }
            });
        }
    </script>

关于javascript - 无法在跨域环境中访问 JS 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10928245/

相关文章:

JavaScript 事件管理,处理全局事件与大量监听器

javascript - 改变word中的字符

javascript - 可以获取iframe的url跨域吗?

iframe - Internet Explorer修复了YouTube嵌入定位问题

javascript - 如何知道 DOM 元素是否在 jquery 范围内?

Javascript 检查函数参数

javascript - AngularJS 中的路由错误

javascript - iframe url 更改时发出警报

javascript - 当 iframe url 更改时如何更改包装器

javascript - 使用 jQuery/javascript/css 更改 flash 视频对象的属性