<!doctype html>
<!--
Copyright 2013 The Chromium Authors
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<html>
<head>
<script type="text/javascript">
// A guest that stores and deletes cookies.
// Note that the embedder has to initiate a postMessage first so that
// the guest has a reference to the embedder's window.
// The window reference of the embedder to send post message reply.
var embedderWindowChannel = null;
// A value that uniquely identifies the guest sending the messages to the
// embedder.
var channelId = 0;
var notifyEmbedder = function(msg_array) {
var msg = msg_array.concat([channelId]);
embedderWindowChannel.postMessage(JSON.stringify(msg), '*');
};
var SPLIT_RE_ = /\s*;\s*/;
var setCookie = function(name, value) { // Just a random future time.
var futureDate = new Date((+new Date) + 10000 * 1000);
document.cookie =
name + '=' + value + ';expires=' + futureDate.toUTCString();
};
var getCookie = function(name) {
var nameEq = name + '=';
var parts = (document.cookie || '').split(SPLIT_RE_);
for (var i = 0; i < parts.length; ++i) {
var part = parts[i];
if (part.lastIndexOf(nameEq, 0) == 0) {
return part.substr(nameEq.length);
}
if (part == name) {
return '';
}
}
return undefined;
};
var addCookies = function() {
var names = ['foo', 'bar'];
var values = ['foovalue', 'barvalue'];
for (var i = 0; i < names.length; ++i) {
window.console.log('setCookie: ' + names[i] + ' = ' + values[i]);
setCookie(names[i], values[i]);
}
notifyEmbedder(['step2.cookies-added']);
};
var onPostMessageReceived = function(e) {
embedderWindowChannel = e.source;
var data = JSON.parse(e.data);
if (data[0] == 'create-channel') {
window.console.log('guest: create-channel');
channelId = data[1];
notifyEmbedder(['channel-created']);
return;
}
window.console.log('guest.onPostMessageReceived: ' + data[0]);
// Tests.
// These logs trigger event listeners in the embedder.
switch (data[0]) {
case 'step1.add-cookies':
window.console.log('guest.' + data[0]);
addCookies();
break;
case 'step3.get-cookies':
window.console.log('guest.' + data[0]);
var retValues = ['step4.got-cookies'];
var cookieValues = [];
for (var i = 1; i < data.length; ++i) {
cookieValues.push(getCookie(data[i]));
}
retValues.push(cookieValues);
notifyEmbedder(retValues);
break;
default:
break;
}
};
window.addEventListener('message', onPostMessageReceived, false);
</script>
</head>
<body>
<div>Guest that stores and retrieves certain cookies.</div>
</body>
</html>