WebSync: Tutorials
On-Demand:
Server:
Fully-working copies of the examples created in these tutorials are available in the
WebSync downloads.
On-Demand: Basic
In this tutorial, you will learn how to integrate WebSync On-Demand into your projects.
There is no server-side code - just plain HTML.
Setting up an HTML page
To get started, we need to create an HTML page to host our JavaScript client.
- Create a new HTML page.
- Add a reference to the client script in the
<head>element.
<head> ... <script type="text/javascript" src="http://sync.frozenmountain.com/client.js?v=2.4.3"></script> ... </head>
Now we can initialize the client and start doing interesting things.
Connecting the client
The first step is to initialize and connect the client.
- Add a new
<script>element to the page somewhere after the script element we just added. - Call
initialize(), passing in your public key as thekeyparameter. - Call
connect()with optionalonSuccessandonFailurehandlers.
<body> ... <script type="text/javascript"> var client = fm.websync.client; // shortcut var util = fm.websync.utilities; // shortcut client.initialize({ key: '11111111-1111-1111-1111-111111111111' // your public key }); client.connect({ onSuccess: function(args) { // optional util.log('Connected!', true); }, onFailure: function(args) { // optional util.log('Connect failed: ' + args.error, true); } }); </script> ... </body>
Ensure you pass in the correct public key for your domain.
Subscribing and publishing
Now that the client is connected, it can subscribe to channels and publish data.
- Call
subscribe()with anonReceivehandler and optionalonSuccessandonFailurehandlers. - Call
publish()with optionalonSuccessandonFailurehandlers.
<body> ... <script type="text/javascript"> // ... continued from above var json = fm.websync.utilities.json; // shortcut client.subscribe({ channel: '/test', onSuccess: function(args) { // optional util.log('Subscribed!', true); }, onFailure: function(args) { // optional util.log('Subscribe failed: ' + args.error, true); }, onReceive: function(args) { util.log('Received data: ' + json.stringify(args.data), true); } }); function publishData() { client.publish({ channel: '/test', data: { text: document.getElementById('text').value }, onSuccess: function(args) { // optional util.log('Published!', true); }, onFailure: function(args) { // optional util.log('Publish failed: ' + args.error, true); } }); } </script> ... </body>
Since the call to
publish() is wrapped in a function, we need a UI element to trigger it.
- Add a button that invokes
publishData().
<body> ... <input type="text" id="text" /> <button onclick="publishData()">Publish</button> ... </body>
Open the page in a couple web browsers and click Publish a few times to see the synchronization!
