获取聊天记录中的消息以显示在messenger Pubnub中

时间:2017-01-28 14:31:05

标签: javascript messaging pubnub

经过2天的折磨,我无法理解如何实际发布存储在pubnub存储帐户中的历史消息,我发布了这个问题。为了尝试理解它最基本的我已经创建了一个聊天应用程序并使用了SDK中描述的历史记录功能,但仍然每次刷新页面时消息都会丢失。我在订阅中尝试了回填和恢复属性,没有运气。我想要做的就是点击chrome上的刷新并查看仍然存在的消息。

<div><input id=input placeholder=you-chat-here /></div>

Chat Output
<div id=box></div>

<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.4.0.min.js"></script>

<script>(function(){
    var pubnub = new PubNub({ publishKey : 'demo', subscribeKey : 'demo' });
    function $(id) { return document.getElementById(id); }
    var box = $('box'), input = $('input'), channel = 'chat';
    pubnub.addListener({

        message: function(obj) {
            box.innerHTML = (''+obj.message).replace( /[<>]/g, '' ) + '<br>' + box.innerHTML
        }});
        pubnub.history({
            channel: 'chat',
            reverse: true, // Setting to true will traverse the time line in reverse starting with the oldest message first.
            count: 100, // how many items to fetch
            callback : function(msgs) {
                pubnub.each( msgs[0], chat );
            }
        },
        function (status, response) {
            // handle status, response
            console.log("messages successfully retreived")
        });

        pubnub.subscribe({channels:[channel],
                          restore: true,
                          backfill: true,
                          ssl: true});

        input.addEventListener('keyup', function(e) {
            if ((e.keyCode || e.charCode) === 13) {
                pubnub.publish({channel : channel, message : input.value,x : (input.value='')});
            }
        });
    })();
</script>

</body>

1 个答案:

答案 0 :(得分:0)

我认为您的history代码不正确。不需要callback因为您的代码响应将在function参数中。 This example is from the JavaScript SDK docs

pubnub.history(
    {
        channel: 'chat',
    },
    function (status, response) {
        var msgs = response.messages;

        if (msgs != undefined && msgs.length > 0) {
            // if msgs were retrieved, do something useful
            console.log(msgs);
        }
    }
);
相关问题