This quickstart demonstrates how to sync changes in a text document between two
HTML elements by using a CollaborativeString object. Below we show you how
to build two separate applications - an unauthenticated app and a fully
collaborative app with Drive persistence. Complete the steps in this page and
you'll have both realtime apps working in just minutes.
Prerequisites
To run this quickstart you'll need:
- A Google account
- Python 1.6 or greater with the ability to run the SimpleHTTPServer module. Another web server that allows you to serve pages from http://localhost:8000 would work as well.
Building An Unauthenticated App
Step 1: Set up the Sample
The Realtime API can work in an unauthenticated mode, called in-memory mode. This allows you to get started with the API without any configuration or login. Creating an in-memory document is as simple as copying the code below into a new file and opening it in a browser.
-
Copy the following source code to a file named
quickstart.html. - Open the file in a browser.
<!DOCTYPE html>
<html>
<head>
<title>Google Realtime Quickstart</title>
<!-- Load Styles -->
<link href="https://www.gstatic.com/realtime/quickstart-styles.css" rel="stylesheet" type="text/css"/>
<!-- Embed the Google API JavaScript loader -->
<script src="https://apis.google.com/js/api.js"></script>
</head>
<body>
<main>
<h1>Realtime Collaboration Quickstart</h1>
<p>Welcome to the quickstart in-memory app!</p>
<textarea id="text_area_1"></textarea>
<textarea id="text_area_2"></textarea>
<p>This document only exists in memory, so it doesn't have real-time collaboration enabled. However, you can persist it to your own disk using the model.toJson() function and load it using the model.loadFromJson() function. This enables your users without Google accounts to use your application.</p>
<textarea id="json_textarea"></textarea>
<button id="json_button" class="visible">GetJson</button>
</main>
<script>
// Load the Realtime API, no auth needed.
window.gapi.load('auth:client,drive-realtime,drive-share', start);
function start() {
var doc = gapi.drive.realtime.newInMemoryDocument();
var model = doc.getModel();
var collaborativeString = model.createString();
collaborativeString.setText('Welcome to the Quickstart App!');
model.getRoot().set('demo_string', collaborativeString);
wireTextBoxes(collaborativeString);
document.getElementById('json_button').addEventListener('click', function(){
document.getElementById('json_textarea').value = model.toJson();
});
}
// Connects the text boxes to the collaborative string.
function wireTextBoxes(collaborativeString) {
var textArea1 = document.getElementById('text_area_1');
var textArea2 = document.getElementById('text_area_2');
gapi.drive.realtime.databinding.bindString(collaborativeString, textArea1);
gapi.drive.realtime.databinding.bindString(collaborativeString, textArea2);
}
</script>
</body>
</html>
Building a Collaborative App in Drive
Step 1: Activate the Drive API
In-memory documents are great for getting started, but to take full advantage of Drive persistence and realtime collaboration, you must register your application with Drive. Let's build on that sample to get a fully collaborative version working. This application needs to be hosted on a webserver. This quickstart guide will demonstrate running the application from a local python webserver. The first step is to activate the Drive API.
Click this button to create a new Cloud Platform project and automatically enable the Drive API:
Take note of the Client ID shown in the resulting dialog.Step 2: Set up the Sample
The collaborative quickstart application consists of one file. The index.html
file provides an HTML container for the realtime application, initializes the
data model with a CollaborativeString object, and listens for events to update
the DOM.
Follow the instructions provided in the tab for index.html.
-
Copy the following source code to a file named
index.html. -
In the location marked
INSERT YOUR CLIENT ID HERE, replace the text with your client ID from the Developers Console.
<!DOCTYPE html>
<html>
<head>
<title>Google Realtime Quickstart</title>
<!-- Load Styles -->
<link href="https://www.gstatic.com/realtime/quickstart-styles.css" rel="stylesheet" type="text/css"/>
<!-- Load the Realtime JavaScript library -->
<script src="https://apis.google.com/js/api.js"></script>
<!-- Load the utility library -->
<script src="https://www.gstatic.com/realtime/realtime-client-utils.js"></script>
</head>
<body>
<main>
<h1>Realtime Collaboration Quickstart</h1>
<p>Now that your application is running, simply type in either text box and see your changes instantly appear in the other one. Open
this same document in a <a onclick="window.open(window.location.href);return false;" target="_blank">new tab</a> to see it work across tabs.</p>
<textarea id="text_area_1"></textarea>
<textarea id="text_area_2"></textarea>
<button id="auth_button">Authorize</button>
</main>
<script>
var clientId = 'INSERT CLIENT ID HERE';
if (!/^([0-9])$/.test(clientId[0])) {
alert('Invalid Client ID - did you forget to insert your application Client ID?');
}
// Create a new instance of the realtime utility with your client ID.
var realtimeUtils = new utils.RealtimeUtils({ clientId: clientId });
authorize();
function authorize() {
// Attempt to authorize
realtimeUtils.authorize(function(response){
if(response.error){
// Authorization failed because this is the first time the user has used your application,
// show the authorize button to prompt them to authorize manually.
var button = document.getElementById('auth_button');
button.classList.add('visible');
button.addEventListener('click', function () {
realtimeUtils.authorize(function(response){
start();
}, true);
});
} else {
start();
}
}, false);
}
function start() {
// With auth taken care of, load a file, or create one if there
// is not an id in the URL.
var id = realtimeUtils.getParam('id');
if (id) {
// Load the document id from the URL
realtimeUtils.load(id.replace('/', ''), onFileLoaded, onFileInitialize);
} else {
// Create a new document, add it to the URL
realtimeUtils.createRealtimeFile('New Quickstart File', function(createResponse) {
window.history.pushState(null, null, '?id=' + createResponse.id);
realtimeUtils.load(createResponse.id, onFileLoaded, onFileInitialize);
});
}
}
// The first time a file is opened, it must be initialized with the
// document structure. This function will add a collaborative string
// to our model at the root.
function onFileInitialize(model) {
var string = model.createString();
string.setText('Welcome to the Quickstart App!');
model.getRoot().set('demo_string', string);
}
// After a file has been initialized and loaded, we can access the
// document. We will wire up the data model to the UI.
function onFileLoaded(doc) {
var collaborativeString = doc.getModel().getRoot().get('demo_string');
wireTextBoxes(collaborativeString);
}
// Connects the text boxes to the collaborative string
function wireTextBoxes(collaborativeString) {
var textArea1 = document.getElementById('text_area_1');
var textArea2 = document.getElementById('text_area_2');
gapi.drive.realtime.databinding.bindString(collaborativeString, textArea1);
gapi.drive.realtime.databinding.bindString(collaborativeString, textArea2);
}
</script>
</body>
</html>
Step 3: Run the sample
- Start a webserver in the directory where you have saved these files. Run the
following command from the directory:
python -m SimpleHTTPServer - Navigate to the python server (http://localhost:8000) or your webserver in a browser.
- Click the Authorize button to authorize access to Drive.
- Open the same URL in a new tab, and view changes to the textareas sync across tabs.