Javascript 跨域环境下无法访问JS功能

Javascript 跨域环境下无法访问JS功能,javascript,iframe,Javascript,Iframe,为了解决JavaScript的跨域安全问题,我实现了以下方法 域名[abc.com] 在domainabc.com上,我有一个名为main\u page.html的页面。其守则如下— <script> function SendMsg(id) { frames["invisible_iframe"].location = "http://xyz.com/invisible_iframe.html#"+id; } </script> <body> &l

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

域名[abc.com]

在domain
abc.com
上,我有一个名为
main\u 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>
<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\u iframe.html
访问函数
Hi()

不可见\u 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>

var sActionText=“”;
函数checkFormMessages()
{
if(location.hash!=sActionText)
{
sActionText=location.hash;
var sAction=“”;
var osplitationtext=sActionText.split(“#”);
sAction=osplitationtext[1];
如果(sAction==“测试”)
{
parent.Hi();
}
}
}
设置间隔(CheckFormMessages,200);
xyz.com上不可见的iFrame
我在
visible\u iFrame.html
中使用隐藏的iFrame,因为我不希望visible\u iFrame.html的URL发生更改

现在我希望当点击
main_page.html
上的按钮时,我会收到警告消息。但事实并非如此。在firefox中显示-访问属性“Hi”的权限被拒绝

奇怪的是当我把
parent.Hi()放在
out
CheckForMessages()
函数,可以访问
Hi()
函数并显示警报框


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

假设你的
onlick
可以处理你的输入(这里只是一个输入错误):从
不可见框架
,你应该用
父框架['visible\u框架].Hi()解决
可见框架
Hi()

目前,
parent.Hi()
尝试访问位于
abc.com
页面上的
Hi()
(因为它是框架的
parent
),因此您会被硬棍同源策略戳到

希望这会有所帮助并起作用;)

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

easyXDM是一个Javascript库,它使开发人员能够 轻松绕过同一原点设置的限制 策略,从而使通信和公开javascript变得容易 API跨越域边界

[这是最好且易于使用的API之一]可用于web应用程序之间的跨域通信。 easyXDM易于使用、重量轻、灵活、编写高质量代码等。我强烈认为,如果您打算继续使用跨域场景,那么您应该采用一个健壮的跨域API,如easyXDM

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

这显然使easyXDM在浏览器支持方面,特别是在旧浏览器方面,具有优越性


使用easyXDM演示跨域访问(Domain1[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>

/**
*请求使用JSON对象
*/
easyXDM.DomHelper.requiresJSON(“../json2.js”);
var远程;
window.onload=函数(){
/**
*窗口加载完成后,开始设置界面
*/
远程=新的easyXDM.接口(/**通道配置*/{
/**
*将url注册到hash.html,这必须是绝对路径
*或相对于根的路径。
*@field
*/
本地:“/hash.html”,
/**
*将url注册到远程接口
*@field
*/
远程:http://YOUR.OTHER.DOMAIN/YOUR_APPLICATION/YourRemoteApplication.html",
/**
*注册生成的IFrame应插入的domeElement
*/
容器:document.getElementById(“嵌入式”)
},/**接口配置*/{
远程:{
remoteApplicationMethod:{},
努普:{
是的
}
},
本地:{
警报信息:{
方法:函数(msg){
警报(msg);
},
是的
}
}
},/**onReady处理程序*/function(){
/**
*调用另一端的方法
*/
remote.noOp();
});
}
函数callRemoteApplicationMethod(值1、值2){
remoteApplicationMethod(值1、值2、函数(结果){
警报(“来自远程应用程序的结果”+结果);
});
}
体内

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

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

<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>
*域[xyz.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>
这应该进入页面YOUR_APPLICATION/yourmoteapplication.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>

/**
*请求使用JSON对象
*/
easyXDM.DomHelper.requiresJSON(“../json2.js”);
无功通道,远程;
/**
*当
<iframe src="http://xyz.com/visible_iframe.html" ...></iframe>
<iframe src="http://xyz.com/invisible_iframe.html" ...></iframe>
parent.Hi();
<!DOCTYPE html>
<html>
<head>
    <script>
    function SendMsg(id) {
        window.frames.invisible.location = 'http://xyz.com/invisible.html#' + id;
    }
    </script>
</head>
<body>
    <input type="button" id="Test" value="Call iFrame" onclick="SendMsg(this.id);">
    <iframe src="http://xyz.com/visible.html" name="visible" height="250" width="500"></iframe>
    <iframe name="invisible" height="0" width="0" style="display:none;"></iframe>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    <script>
    function Hi() {
        alert('Hi there!');
    }
    </script>
</head>
<body>
    <h1>Visible on xyz.com</h1>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    <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.frames.visible.Hi();
            }
        }
    }
    setInterval(CheckForMessages, 200); 
    </script>
</head>
<body>
    <h1>Invisible on xyz.com</h1>
</body>
</html>
       main
       /  \
      /    \
visible    invisible
parent.frames.visible.Hi()
<script>
    function sendMsg( id ) {
       frames["invisible_iframe"].location = "//xyz.com/mid_level.html#" + id;
    }

    window.ACTIONS = {
        Test: function() {
            alert("hello");
            // This action could also start an interaction with another
            // visible iframe by setting a hash, etc
        }
    };
</script>
<input type="button" id="Test" value="Call iFrame" onclick="sendMsg(this.id);">
<iframe name="invisible_iframe" height="0" width="0" frameborder="0" style="visibility:hidden;" src="//xyz.com/mid_level.html"></iframe>
<script>
    function sendMsg( id ) {
       frames["invisible_iframe"].location = "//abc.com/low_level.html#" + id;
    }

    var sActionText = "";
    function checkForMessages() {
       if(location.hash != sActionText) {
         sActionText = location.hash.replace(/^#/, "");
         location.hash = "";

         sendMsg(sActionText);
       }
    }

    setInterval(checkForMessages, 20); 
</script>
<iframe name="invisible_iframe" height="0" width="0" frameborder="0" style="visibility:hidden;" src="//abc.com/low_level.html"></iframe>
<script>
    function runActionInTop( action ) {
        try {
            window.top.ACTIONS[action]();
        } catch ( err ) {
            // Bad action!
        }
    }

    var sActionText = "";
    function checkForMessages() {
       if(location.hash != sActionText) {
         sActionText = location.hash.replace(/^#/, "");
         location.hash = "";

         runActionInTop(sActionText);
       }
    }

    setInterval(checkForMessages, 20); 
</script>
<?php
  $external-site = file_get_contents('http://xyz.com/');
  echo $external-site;
?>