跨域Dom查询
位于a.my.com的a.php文件
<iframe style="width:0;height:0" src="http://b.my.com/b.php"></iframe>
<script>
$(function(){
document.domain = 'my.com';//设置域名
})
</script>
位于b.my.com的b.php文件
<!-- 自行引入jQuery -->
<script src="jquery/lib.js"></script>
<script>
$(function(){
document.domain = 'my.com';//设置域名
var browser_version = get_browser_version();
var browser = browser_version[0];
var version = browser_version[1];
var br_detect = 1;//浏览器监测
if (browser == 'MSIE') {
if (parseInt(version) < 9) {
br_detect = 0;/* IE 9 以下不支持 */
}
}
if (br_detect) {
bindEvent_('a', 'mousedown');
bindEvent_('button', 'mousedown');
}
})
/* 获取浏览器及版本 */
function get_browser_version() {
var N = navigator.appName, ua = navigator.userAgent, tem;
var M = ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
if (M && (tem = ua.match(/version\/([\.\d]+)/i)) != null) {
M[2] = tem[1];
}
M = M ? [M[1], M[2]] : [N, navigator.appVersion, '-?'];
return M;
}
function bindEvent_(tag, eventType) {
//注意这里的parent.document,将事件绑定在父页面上
$(tag, parent.document).on(eventType, function(){
var this_ = $(this);
console.log('触发了【' + eventType + '】事件:');
console.log('ID:' + (this_.attr('id') || ''));
console.log('class:' + (this_.attr('class') || ''));
console.log('href:' + (this_.attr('href') || ''));
console.log('标签:' + this_[0].tagName);
console.log('名称:' + (this_.text() || this_.value()));
//do ajax将数据存入数据库
})
}
</script>
当点击a页面(父页面)的a、button标签时,会触发bindEvent_事件,将数据传入b页面,通过ajax保存到b系统中的数据库中,实现用户行为记录
使用postMessage跨域传值
<iframe style="width:0;height:0" id='myframe' name='myframe' src="http://b.my.com/b.php"></iframe>
<script>
$(function(){
//发送信息
var frame = window.frames['myframe'];
frame.postMessage('发送信息', 'http://b.my.com');
//监听信息
window.addEventListener('message', function(e) {
console.dir('接收信息:' + e.data);
}, false);
})
</script>
参考