前端同源条件下跨浏览器标签页 跨Iframe传值解决方案

场景: 有A,B两个页面 假设B页面的操作要修改A页面的内容  这里写一个简单实现方法的demo 

localStorage 保存数据时会触发一个storage事件(数据更新时 需要两次数据不一致才能触发 可以加时间戳解决)  

common.js

var Tool = function(){};
/*
 * 发送指令 
 * */
Tool.prototype.emitInstruction = function(pageName){
    var pageData = {
        page: pageName,
        timeStamp: Date.now()
    };
    localStorage.setItem('PAGE-COMMON-DATA',JSON.stringify(pageData));
};
/*
 * 监听storage事件 接到指令时执行回调方法
 *
 * */
Tool.prototype.listenInstruction = function(pageName,callback){
    window.addEventListener("storage",function(e){
        var item = JSON.parse(localStorage.getItem("PAGE-COMMON-DATA"));
        if(item.page === pageName){
            callback();
        }
    })
};
window.tool  = new Tool();

页面A

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<div id="text">

</div>
</body>
<script src="common.js"></script>
<script>
tool.listenInstruction('A.html',function(){
    document.getElementById('text').innerHTML = '支付成功';
});
</script>
</html>

页面B

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<div id="text">
<button id="paySuccess">支付成功</button>
</div>
</body>
<script src="common.js"></script>
<script>
    document.getElementById('paySuccess').addEventListener('click',function(){
        tool.emitInstruction('A.html');
    });
</script>
</html>

 

posted @ 2017-02-13 15:07  灰头像  阅读(673)  评论(0)    收藏  举报