【问题标题】:Getting messages in chat history to display in messenger Pubnub获取聊天记录中的消息以显示在 Messenger Pubnub 中
【发布时间】:2017-06-14 03:15:46
【问题描述】:

经过 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>

【问题讨论】:

  • 检查你的response.messages,它实际上是在返回你的消息,但它是对象,不确定为什么回调不能从历史方法中工作,

标签: javascript messaging pubnub


【解决方案1】:

编辑:更新的链接已损坏。新版本的history函数被称为fetchMessages

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

// deprecated function
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);
        }
    }
);

// latest function (response output format has changed)
pubnub.fetchMessages(
    {
        channels: ['chat']
    },
    (status, response) => {
        console.log(msgs);
    }
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 2014-01-05
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    相关资源
    最近更新 更多