Skip to content

Instantly share code, notes, and snippets.

@iahu
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iahu/d9567159f284fe8afb2a to your computer and use it in GitHub Desktop.
Save iahu/d9567159f284fe8afb2a to your computer and use it in GitHub Desktop.
window.name跨域小例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
body {padding:0 20px;margin: 0;font-family: '黑体', sans-serif;}
code {border: 1px solid #e3e3e3;padding: 1px 2px;}
#res {height: 5em;border: 1px solid #999;}
</style>
</head>
<body>
<h2>window.name跨域小例</h2>
<h3>说明</h3>
<ol>
<li>proxy.html是本域下的代理文件</li>
<li>response.html是要跨域请求的页面(本例是http://q.com/response.html),此页面可动态生成要返回的数据</li>
<li>可以在本地启html服务,再配上不同的hosts来模拟跨域页面</li>
</ol>
<br>
<button id="btn">获取数据</button>
<h5>返回数据:</h5>
<div id="res"></div>
<script>
var resDiv = document.getElementById('res');
function send(url, cb) {
var ifr = document.createElement('iframe'),
state = 0,
clearIfr = function () {
try {
ifr.contentWindow.document.write('');
ifr.contentWindow.close();
document.body.removeChild(ifr);
} catch(e){}
},
getData = function () {
var data;
try {
data = ifr.contentWindow.name;
clearIfr();
if (cb && typeof cb === 'function') {
cb(data);
}
} catch(e) {
// alert(e);
}
};
document.body.appendChild(ifr);
ifr.style.display = 'none';
function handler() {
if (state === 1) {
getData();
} else if (state === 0) {
state = 1;
ifr.contentWindow.location = './proxy.html';
}
}
if (ifr.addEventListener) {
ifr.addEventListener('load', handler);
}
if (ifr.attachEvent) {
ifr.attachEvent('onload', handler);
} else {
ifr.onload = handler;
}
ifr.src = url;
}
document.getElementById('btn').onclick = function (e) {
send('http://a.com/response.html', function(res) {
resDiv.innerText = res;
});
}
</script>
</body>
</html>
<html>
<body>
<!-- empty html -->
</body>
</html>
<html>
<body>
<script>
window.name = '{"msg": "消息"}';
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment