简体   繁体   中英

JavaScript Not Sending Info To WebSocket When Page is Loaded

I am having trouble sending information of a session cookie when loading a page.

Here is how the function executes

<body onload="example();">

Here is the function it self

function example() {
  websocket.send("<?php print($_SESSION['example']) ?>")
}

I've tried this way as well, but still does not work.

function example() {
  websocket.send("Test")
}

I also tried calling this function when a button is clicked and it does work.

I was thinking maybe the connection to the websocket is not fast enough and the example(); function is called before the connection is established. Please let me know how I can make this work.

This a complete example of how to connect to a WebSocket from the onload document event:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>WebSocket Sample</title>
    <script type="text/javascript">
    function example()
    {
        // open websocket
        var socket = new WebSocket('ws://localhost:80');

        socket.onopen = function() {
            console.log("onopen!");
            // Web Socket is connected. send an initial random message.
            socket.send("Hello!");
        };
    }
    </script>
</head>
<body onload="example();">
    <h1>Title</h1>
</body>
</html>

I found out that the connection stablish after the execution of the function so what I simply did was setTimeout , even duh its not a good practice, it will be enough for the project am doing. Here is short version of my solution.

<!DOCTYPE HTML>
<HTML>
    <HEAD>
        <script language="javascript" type="text/javascript">
           function example() {
               function sendUser() {
                setTimeout(
                   function() {
                   websocket.send("Wroked!")
                   }, 1000);
                }
           }
        </script>
    </HEAD>
    <BODY onload="example();">
    </BODY>
</HTML>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM