无奈的页面通信

为了与stf页面通信,今天扣扣索索写了这个坑爹的代码,感觉超级费劲啊

define([], function () {

    var Ken = {};
    var debug = function(v){console.info(v)};

    var checkis = !!window.postMessage;
    var inited = false;

    // 定义通道信息
    var channels  = {};

    // 定义ping命令的序列集
    var pings = {};

    Ken.init = function()
    {
        // 防止重复调用
        if (inited) return;

        inited = true;
        if ( !checkis )
        {
            alert("您的浏览器当前不支持此功能");
            return;
        }

        console.log('jsbridge init ...')

        // 绑定消息接收器
        if(window.addEventListener)
        {
            window.addEventListener('message', onRecieveMessage, false);
        }
        else
        {
            window.attachEvent('message', onRecieveMessage, false);
        }
    }

    Ken.createChannel = function(channelName, settings)
    {
        var defaults = {
            winId: false,
            isIframe: true,
            targetOrigin: '*',
            ping: false,
            onRecieveMessage: function(message)
                {
                    console.log('wahaha: ', $.toJSON(message));
                }
        }

        channels[ channelName ] = $.extend(defaults, settings);

        console.log('bind channel:', channelName, channels[ channelName ]);
    }

    Ken.sendMessage = function(channelName, data)
    {
        if (!inited)
        {
            alert('Please init jsbridge');
            return;
        }

        if ( !checkis )
        {
            console.log('Un support sendMessage in:', channelName, data);
            return;
        }

        var channel = channels[ channelName ];

        if (!channel)
        {
            //alert('Un define channel: ', channelName);
            console.log('Un define channel: ', channelName);
            return;
        }

        var winDom = document.getElementById(channel.winId);

        if (!winDom)
        {
            console.log('Cannot find element: ', channel.winId);
            return;
        }

        var rawData = $.toJSON({channel: channelName,message: data});

        console.log('sendMessage to ' + channelName, rawData);
        
        try
        {
            if (channel.isIframe)
            {
                winDom.contentWindow.postMessage(rawData, channel.targetOrigin);
            }
            else
            {
                winDom.postMessage(rawData, channel.targetOrigin);
            }           
        }
        catch(e)
        {
            console.log('sendMessage has error: ', e);
            return;
        }
    }

    Ken.ping = function(channelName, success, failed)
    {
        var channel = channels[ channelName ];

        if (!channel)
        {
            //alert('Un define channel: ', channelName);
            console.log('Un define channel: ', channelName);
            return;
        }

        // 轮询 ping 目标通道
        if (!channel.ping)
        {
            var funcName = 'ping' + channelName;

            if (!pings[channelName])
            {
                $.jsbridge[funcName] = function(){
                    Ken.sendMessage(channelName, 'ping');
                }
            }

            var intervalCode = "$.jsbridge." + funcName + "()";

            pings[channelName] = {
                intervalCode: intervalCode,
                intervalName: false,
                success: success
            };

            // 加定时器
            pings[channelName]['intervalName'] = window.setInterval(intervalCode,1500);
        }
    }

    function onRecieveMessage(event) {
        // console.log('listen messageEvent:', event);
        var data = null;
        try {
            data = $.parseJSON(event.data);
        } catch (e) {}

        if (data && data.channel)
        {
            var channelName = data.channel;
            var channel = channels[ channelName ];

            if (!channel)
            {
                console.log('Un define channel: ', channelName);
                return;
            }

            // 如果有数据响应,则认为对方服务是可用的
            channels[ channelName ].ping = true;
            if (pings[channelName])
            {
                var intervalName = pings[channelName].intervalName;

                try{                    
                    window.clearInterval(intervalName);
                    pings[channelName].success();
                    pings[channelName] = false;
                }catch(e){}
            }

            console.log(channelName + ' onRecieveMessage: ', data.message);

            return channel.onRecieveMessage(data.message);
        }
    }

    $.jsbridge = {};

    return Ken;
});

你可能感兴趣的:(无奈的页面通信)