跨域使用window.name

文章目录:

    跨域-知识

    跨域-使用JSONP

    跨域-使用js文件

    跨域-使用window.name

    跨域-使用Proxy page或Cross Frame      


    实现原理请看“ 跨域-知识”-window.name节。实现方法如下。

    1、在A域的CrossByWindowName.aspx页面中创建一个iframe,把其src指向B页域的CrossByWindowName.aspx页面。通过CrossByWindowName.aspx中的按钮得到通过window.name传回的值。代码如下。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CrossByWindowName.aspx.cs"
    Inherits
="IframeTest.CrossByWindowName" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <div id="cnt">
        <iframe id="ifr" src="http://oatest.mic.com.tw/gsc/CrossByWindowName.aspx" width="100%"
            height
="500px"></iframe>
    </div>
    <%--通过此按钮获得Window.Name值,实际得到是在iframe的onload事件中得到。
    主要是当点击后,iframe会跳转到本地页面,这样就在同一个域中,这时iframe的load完成后,就可以通过window.name得到值
--%>
    <input id="btnGetWindowName" type="button" value="GetWindowName" onclick="GetWindowName()" />
</body>
</html>
<script type='text/javascript'>
    
var state = 0;
    
var iframe = document.getElementById('ifr');
    
//给iframe设置onload事件。通过onload事件
    if (iframe.attachEvent) {
        iframe.attachEvent(
"onload"function () {
            
if (state == 1) {
                
var data = iframe.contentWindow.name;    // 读取数据
                alert(data);
            }
        });
    } 
else {
        iframe.onload 
= IframLoadFn;
    }

    
//onload事件
    var IframLoadFn = function () {
        
if (state == 1) {
            
var data = iframe.contentWindow.name;    // 读取数据
            alert(data);
        } 
else if (state == 0) {
            state 
= 1;
            iframe.contentWindow.location 
= "Proxy.htm";    // 设置的代理文件,此文件不一定要真实存在
        }
    };

    
//state=1 时,表示取数据。0表示
    var GetWindowName = function () {
        state 
= 1;
        iframe.contentWindow.location 
= "Proxy.htm";    // 设置的代理文件,此文件不一定要真实存在
    }
</script>

    2、在B域的CrossByWindowName.aspx页面中通过一个按钮及输入框给window.name赋值。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CrossByWindowName.aspx.cs" Inherits="ExtNetStudy.CrossByWindowName" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        
var WindowClick = function () {
            window.name 
= document.getElementById("txtCookie").value;
            alert(window.name);
        }
    
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Winddow.Name:
        <input id="txtCookie" type="text" value="Window.name Value" />
        <input id="btnWindow" type="button" value="SetWindow" onclick="WindowClick()" />
    </div>
    </form>
</body>
</html>
原文地址:https://www.cnblogs.com/scottckt/p/2246787.html