javascript - 将peerJS函数分配给按钮

标签 javascript html peerjs

我试图将peerJS“发布”函数分配给按钮单击事件,但它不会将消息发送到其他浏览器页面。

如果我直接调用发布函数而不是通过单击事件,我会在其他浏览器上收到一条消息。

发送方代码:

<body>
    <script>
        var peer = new Peer('controller', {key: 'xxxxxxxxxxxxxxx'});
        var conn = peer.connect('game');
        
        function publish(m) {
            conn.on('open', function(){
                conn.send(m);
            }); 
        };
    
        //This is working:
        publish("It's working 😄");
    
    </script>

    <button onclick="publish('Not working 😞')">send</button>
</body>

接收端代码:

<script>
    var peer = new Peer('game', {key: 'xxxxxxxxxxxx'});
        peer.on('connection', function(conn) {
            conn.on('data', function(m){
            // Will print the value of (m)
            console.log(m);
        });
    });
</script>

最佳答案

好吧, 问题解决了!我需要重构我的代码并在对等连接 block 内声明 publish() 函数。

以下是将功能分配给按钮的代码:

<script>
    $( document ).ready(function() {
        var peer = new Peer('controller', {key: 'xxxxxxxxxx'});
        var conn = peer.connect('myGame');
        var publish;
        
        conn.on('open', function(){
            publish = function(message) {
                conn.send(message);
            }
        }); 
    })
</script>

HTML

<button onclick="publish('Now I'm working!')">Send<button>

关于javascript - 将peerJS函数分配给按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23523338/

相关文章:

javascript - PeerJS 对等端未接收数据

linux - 没有浏览器的 Raspberry Pi 上的 WebRTC

javascript - 在导航到新页面之前,如何让 Angular 休眠 5 秒?

javascript - 根据媒体是播放还是暂停来更改按钮的文本?

javascript - 在按钮下

html - Position Absolute 如何使其居中,无论以何种屏幕分辨率查看?

javascript - 在 Cypress 中随时随地创建一定大小的文件

Javascript 无法识别 SWT BrowserFunction

html - 如何在不滚动的情况下将布局固定到浏览器窗口

node.js - WebSocket (Socket.io) 连接错误 - 失败 : Connection closed before receiving a handshake response